i have a JSON dict list that i want to extract a value from based on another value in the same dict. I have tried multiple ways of getting the value but i can not find anything that works. the dict list can have variable number of dicts, and therefore it doesn't always give the correct answer when use numbered brackets. (['objectEntries'][0]['attributes'][5]["subValue"][0]['displayValue'])
The objectEntries dict list contain more dicts, but I shaved it for size. I will loop through all the dicts to extract the same value.
i have a json:
{
"objectEntries": [
{
"label": "test",
"attributes": [
{
"id": 0,
},
{
"id": 1,
},
{
"id": 2,
},
{
"id": 3,
},
{
"id": 4,
},
{
"Id": 5,
"subValue": [
{
"displayValue": "This",
}
],
"objectId": 26085
},
],
"name": "test"
}
{
...
}
]
}
where I want to extract the value "This" from subValue.displayValue where objectEntries.attributes.id = 5. I am fairly new to JSON, so any help pushing me in the right direction would be appreciated.
What I have made so far:
import json
import pandas as pd
with open('fulldump.json', 'r') as f:
data = json.load(f)
for object in data['objectEntries']:
name = object['name']
get = object['attributes'][5]['subValue'][0]['displayValue']
table.append([name, get])
df = pd.DataFrame(table, columns=['Name', 'Get'])
The value from varaible "get" is usually correct, but for some objectEntries, one or more dicts in the attributes are missing, which makes get reading the wrong value.
CodePudding user response:
Maybe you could just check for the key instead of guessing the correct dictionary to manipulate?
For instance
import json
import pandas as pd
with open('fulldump.json', 'r') as f:
data = json.load(f)
for object in data['objectEntries']:
name = object['name']
relevant_dict = filter(lambda x: 'subValue' in x, object['attributes'])[0]
get = relevant_dict['subValue'][0]['displayValue']
table.append([name, get])
df = pd.DataFrame(table, columns=['Name', 'Get'])
This answer assumes that only one of the attributes entry will contain the wanted key though
Edit:
If you want to specifically get the item with Id 5 each time, you can adapt the filter as follow:
import json
import pandas as pd
with open('fulldump.json', 'r') as f:
data = json.load(f)
for object in data['objectEntries']:
name = object['name']
relevant_dict = filter(lambda x: x['Id'] == 5, object['attributes'])[0]
get = relevant_dict['subValue'][0]['displayValue']
table.append([name, get])
df = pd.DataFrame(table, columns=['Name', 'Get'])