can't print the value of json object in django - python

I have this json object in ajax_data variable
{
"columns[0][data]": "0",
"columns[1][name]": "",
"columns[5][searchable]": "true",
"columns[5][name]": "",
"columns[4][search][regex]": "false",
"order[0][dir]": "asc",
"length": "10",
}
I have converted it using json.loads() function like.
ajax_data = json.loads(ajax_data)
I want to get the value if "order[0][dir]" and "columns[0][data]" but if i print it using
ajax_data['order'][0]['dir]
its giving error :
KeyError at /admin/help
'order'
But same code works if i access it for length key then it works.

The keys you have used are actually not a good way of implementation.
{
"columns[0][data]": "0",
"columns[1][name]": "",
"columns[5][searchable]": "true",
"columns[5][name]": "",
"columns[4][search][regex]": "false",
"order[0][dir]": "asc",
"length": "10",
}
Instead of this you should hav gone for
{
"columns": [
{"data": "0", "name": "", "searchable": "true", "name": "", "search": {
"regex": "false"}
},
{"data": "0", "name": "", "searchable": "true", "name": ""," search": {
"regex": "false"}},
{"data": "0", "name": "", "searchable": "true", "name": "", "search": {
"regex": "false"}},
{"data": "0", "name": "", "searchable": "true", "name": "", "search": {
"regex": "false"}},
{"data": "0", "name": "", "searchable": "true", "name": "", "search": {
"regex": "false"}},
{"data": "0", "name": "", "searchable": "true", "name": "", "search": {
"regex": "false"}},
],
"order": [
{"dir": "asc"}
],
"length": "10"
}
In this case ajax_data['order'][0]['dir] will result in value "asc"
For your current implementation the key is "order[0][dir]"
That is go for
ajax_data["order[0][dir]"]
Hope you understood the issue.
Structuring of json is very important when dealing with APIs. Try to restructure your json which will help for future too.

That's because length is a key in that json object, and order is not. The key names are the entire strings inside the quotes: columns[0][data], order[0][dir], etc.
Those are unusual key names, but perfectly valid.

Related

How to compare 2 JSON strings and store what changed in a variable Python

I have a JSON string that is a response to a GET request:
[
{
"symbol": "cosmic2",
"name": "Cosmic Condos",
"description": "Some cosmic condos",
"image": "https://bafybeif3tacmhinsivylzrrxskwshwufysst3s6np3y2ar3qagpmliw374.ipfs.dweb.link/72.png?ext=png",
"twitter": "",
"discord": "",
"website": "",
"categories": []
}
]
And after a while it becomes :
[
{
"symbol": "cosmic2",
"name": "Cosmic Condos",
"description": "Some cosmic condos",
"image": "",
"twitter": "",
"discord": "",
"website": "",
"categories": []
},
{
"symbol": "test_lp_1",
"name": "Test Launchpad 1",
"description": "3 Stages",
"image": "",
"categories": [
"launchpad"
]
}
]
How do I store the second part that was added in a variable and later work with it?

Filter json response from http request to only specific value then select the largest 'id' value from all results

I have a Python script where I would like to filter Python with a http get and I would like to filter the response data for only specific values. The json response example is below:
{
"id": "38",
"name": "Report1",
"description": "",
"reportDefinitionID": "-1",
"jobID": "105600",
"type": "csv",
"status": "Completed",
"creator": {
"id": "1",
"username": "btest",
"firstname": "bob",
"lastname": "test"
},
{
"id": "39",
"name": "Report2",
"description": "",
"reportDefinitionID": "-1",
"jobID": "113218",
"type": "csv",
"status": "Completed"
"creator": {
"id": "1",
"username": "btest1",
"firstname": "Bob",
"lastname": "test1"
},
"id": "49",
"name": "Report1",
"description": "",
"reportDefinitionID": "-1",
"jobID": "113219",
"type": "csv",
"status": "Completed"
"creator": {
"id": "1",
"username": "btest1",
"firstname": "Bob",
"lastname": "test1"
}
I would like to filter the above json to only show a report by name. For example if there is a Python filter that would only allow me to filter for a report by the name of "Report1". If I filtered on name of "Report1". I would expect to following to be to be returned below:
{
"id": "38",
"name": "Report1",
"description": "",
"reportDefinitionID": "-1",
"jobID": "105600",
"type": "csv",
"status": "Completed",
"creator": {
"id": "1",
"username": "btest",
"firstname": "bob",
"lastname": "test"
},
"id": "49",
"name": "Report1",
"description": "",
"reportDefinitionID": "-1",
"jobID": "113219",
"type": "csv",
"status": "Completed"
"creator": {
"id": "1",
"username": "btest1",
"firstname": "Bob",
"lastname": "test1"
}
For the final part of the script I would like to compare the 'id' field to show the largest value for example id 38 vs id 49 and then output the json for the largest in this case id 49. I would like it output
},
"id": "49",
"name": "Report1",
"description": "",
"reportDefinitionID": "-1",
"jobID": "113219",
"type": "csv",
"status": "Completed"
"creator": {
"id": "1",
"username": "btest1",
"firstname": "Bob",
"lastname": "test1"
}
For the last part i would just like to save the id value '49' to a variable in Python.
So far what I have below is:
response_data = response.json()
input_dict = json.dumps(response_data)
input_transform = json.loads(input_dict)
# Filter python objects with list comprehensions
sort1 = sorted([r.get("id") for r in input_transform if r.get("name") == "Report1"], reverse=True)[0]
# Print sorted JSON
print(sort1)
I updated my code and now I'm getting the error below:
'str' object has no attribute 'get'
I researched it and can not figure out what I'm doing now and how to get past it.
You need to get the ID in the listcomp as bellow:
sorted([r.get("id") for r in sample if r.get("name") == "Report1"], reverse=True)[0]

Python Json Parsing Key Value Filtering

How can I only get the lines which do not have "popup:" in them?
json_data = json.loads(raw_json, strict=False)
This is the data:
{
"259655": { "params": ["OIL", "9,5"], "availability": "1", "reload": ""},
"259656": { "params": ["OIL", "10"], "availability": "1", "reload": ""},
"259659": { "params": ["OIL", "11,5"], "availability": "1", "reload": ""} ,
"259661": { "params": ["SALT", "5"], "availability": "1", "reload": "", "popup": "" },
"259662": { "params": ["SALT", "5,5"], "availability": "1", "reload": "", "popup": "" },
"259663": { "params": ["SALT", "6"], "availability": "1", "reload": "", "popup": "" },
}
Here's a simple solution using dict comprehension to create a new dict without values that contain "popup" keys
filtered_dict = {i: json_data[i] for i in json_data if "popup" not in json_data[i]}

Parsing json into a list of values

I have a program that takes some file and transforms it into a json format.
Im trying to get all the values of certain keys into a list but, because the format of the json file has a bunch of keys that are present multiple times, I cant find a way to do it properly.
My json file looks like this
{
"data": {
"__schema": {
"queryType": {
"fields": [
{
"description": "",
"name": "project"
},
{
"description": "",
"name": "projectEventFeed"
},
{
"description": "",
"name": "projectEventFeedFetchMore"
},
{
"description": "",
"name": "projectRecentEventFeed"
},
{
"description": "",
"name": "unseenProjectActivityCount"
},
{
"description": "",
"name": "projectFiles"
},
{
"description": "",
"name": "projectFilesIdSet"
},
{
"description": "",
"name": "projectFileMessages"
},
{
"description": "",
"name": "projectUserStatus"
},
{
"description": "",
"name": "projectFileScribble"
},
{
"description": "",
"name": "user"
},
{
"description": "",
"name": "viewer"
},
{
"description": "",
"name": "profile"
},
{
"description": "",
"name": "site"
},
{
"description": "",
"name": "designers"
},
{
"description": "",
"name": "predictImageCategory"
},
{
"description": "",
"name": "getPortfolioDesign"
}
]
}
}
}
}
My goal is to get all the name values into a list.
Before turning the file into json, I tried getting that with regex but failed.
With json format I tried the following
map(lambda parsed_json: parsed_json['data']['__schema']['queryType']['fields']['name'], List)
Im getting List from typing
But when i want to turn the map into a list, I get
TypeError: Parameters to generic types must be types. Got 0.
From the conversion.
You could just use list comprehension on the nested 'fields' key in the dict you have converted from your json.
d = {"data": {"__schema": {"queryType": {"fields": [{"description": "", "name": "project"}, {"description": "", "name": "projectEventFeed"}, {"description": "", "name": "projectEventFeedFetchMore"}, {"description": "", "name": "projectRecentEventFeed"}, {"description": "", "name": "unseenProjectActivityCount"}, {"description": "", "name": "projectFiles"}, {"description": "", "name": "projectFilesIdSet"}, {"description": "", "name": "projectFileMessages"}, {"description": "", "name": "projectUserStatus"}, {"description": "", "name": "projectFileScribble"}, {"description": "", "name": "user"}, {"description": "", "name": "viewer"}, {"description": "", "name": "profile"}, {"description": "", "name": "site"}, {"description": "", "name": "designers"}, {"description": "", "name": "predictImageCategory"}, {"description": "", "name": "getPortfolioDesign"}]}}}}
fields = [f['name'] for f in d['data']['__schema']['queryType']['fields']]
print(fields)
# ['project', 'projectEventFeed', 'projectEventFeedFetchMore', 'projectRecentEventFeed', 'unseenProjectActivityCount', 'projectFiles', 'projectFilesIdSet', 'projectFileMessages', 'projectUserStatus', 'projectFileScribble', 'user', 'viewer', 'profile', 'site', 'designers', 'predictImageCategory', 'getPortfolioDesign']

How to delete on square from json file in python?

I have an extra last square } in a big json file, I need to remove it by using python :
{
"layers": {
"frame": {
"frame.interface_id": "0",
"frame.encap_type": "127",
"frame.time": "Oct 10, 2017 18:05:51.620568000 Central European Daylight Time",
"frame.offset_shift": "0.000000000",
"frame.time_epoch": "1507651551.620568000",
"frame.time_delta": "0.324011000",
"frame.time_delta_displayed": "0.324011000",
"frame.time_relative": "29.248970000",
"frame.number": "38",
"frame.len": "64",
"frame.cap_len": "64",
"frame.marked": "0",
"frame.ignored": "0",
"frame.protocols": "wpan:6lowpan:ipv6:ipv6.hopopts:udp:data",
"frame.coloring_rule.name": "UDP",
"frame.coloring_rule.string": "udp"
},
"wpan": {
"wpan.frame_length": "66",
"wpan.fcf": "0x0000dc41",
"wpan.fcf_tree": {
"wpan.frame_type": "0x00000001",
"wpan.security": "0",
"wpan.pending": "0",
"wpan.ack_request": "0",
"wpan.pan_id_compression": "1",
"wpan.seqno_suppression": "0",
"wpan.ie_present": "0",
"wpan.dst_addr_mode": "0x00000003",
"wpan.version": "1",
"wpan.src_addr_mode": "0x00000003"
},
"wpan.seq_no": "8",
"wpan.dst_pan": "0x0000abcd",
"wpan.dst64": "00:21:2f:3c:c6:b5:00:01",
"wpan.src64": "00:21:2f:3c:c6:b5:00:7e",
"wpan.fcs_ok": "1"
},
"6lowpan": {
"IPHC Header": {
"6lowpan.pattern": "0x00000003",
"6lowpan.iphc.tf": "0x00000003",
"6lowpan.iphc.nh": "0",
"6lowpan.iphc.hlim": "0x00000002",
"6lowpan.iphc.cid": "1",
"6lowpan.iphc.sac": "1",
"6lowpan.iphc.sam": "0x00000003",
"6lowpan.iphc.m": "0",
"6lowpan.iphc.dac": "1",
"6lowpan.iphc.dam": "0x00000003",
"6lowpan.iphc.sci": "0x00000000",
"6lowpan.iphc.dci": "0x00000000"
},
"6lowpan.next": "0x00000000",
"6lowpan.src": "::221:2f3c:c6b5:7e",
"6lowpan.dst": "::221:2f3c:c6b5:1"
},
"ipv6": {
"ipv6.version": "6",
"ip.version": "6",
"ipv6.tclass": "0x00000000",
"ipv6.tclass_tree": {
"ipv6.tclass.dscp": "0",
"ipv6.tclass.ecn": "0"
},
"ipv6.flow": "0x00000000",
"ipv6.plen": "39",
"ipv6.nxt": "0",
"ipv6.hlim": "64",
"ipv6.src": "::221:2f3c:c6b5:7e",
"ipv6.addr": "::221:2f3c:c6b5:7e",
"ipv6.src_host": "::221:2f3c:c6b5:7e",
"ipv6.host": "::221:2f3c:c6b5:7e",
"ipv6.dst": "::221:2f3c:c6b5:1",
"ipv6.addr": "::221:2f3c:c6b5:1",
"ipv6.dst_host": "::221:2f3c:c6b5:1",
"ipv6.host": "::221:2f3c:c6b5:1",
"Source GeoIP: Unknown": "",
"Destination GeoIP: Unknown": "",
"ipv6.hopopts": {
"ipv6.hopopts.nxt": "17",
"ipv6.hopopts.len": "0",
"ipv6.hopopts.len_oct": "8",
"ipv6.opt": {
"ipv6.opt.type": "99",
"ipv6.opt.type_tree": {
"ipv6.opt.type.action": "1",
"ipv6.opt.type.change": "1",
"ipv6.opt.type.rest": "0x00000003"
},
"ipv6.opt.length": "4",
"ipv6.opt.rpl.flag": "0x00000000",
"ipv6.opt.rpl.flag_tree": {
"ipv6.opt.rpl.flag.o": "0",
"ipv6.opt.rpl.flag.r": "0",
"ipv6.opt.rpl.flag.f": "0",
"ipv6.opt.rpl.flag.rsv": "0x00000000"
},
"ipv6.opt.rpl.instance_id": "0x0000001e",
"ipv6.opt.rpl.sender_rank": "0x00000200"
}
}
},
"udp": {
"udp.srcport": "30002",
"udp.dstport": "3000",
"udp.port": "30002",
"udp.port": "3000",
"udp.length": "31",
"udp.checksum": "0x00007ca5",
"udp.checksum.status": "2",
"udp.stream": "17"
},
"data": {
"data.data": "2f:14:02:15:20:ed:1a:05:02:40:29:5c:ab:41:cc:23:c7:42:10:d8:eb:41:45",
"data.len": "23"
}
}
}
}
,
How could I remove it please?
I would be very grateful if you help me please?
First thing first: having one extra closing brace means this is not valid json, so the best thing to do would be to cure the problem at the source. If this comes verbatim from some api then contact the tech staff, if this comes from your own code then fix it where this extra brace is introduced.
This being said, assuming your json is stored as a string data, then removing the last closing brace is as simple as
data = data.strip().rstrip("}")
If this is part of an automated process and you only sometimes have this extraneaous brace, you can test before cleaning up:
if data.count("}") > data.count("{"):
data = data.strip().rstrip("}")

Categories

Resources