I’m using Yahoo Placemaker API which gives different structure of json depending on input.
Simple json file looks like this:
{
'document':{
'itemDetails':{
'id'='0'
'prop1':'1',
'prop2':'2'
}
'other':{
'propA':'A',
'propB':'B'
}
}
}
When I want to access itemDetails I simply write json_file[‘document’][‘itemDetails’].
But when I get more complicated response, such as
{
'document':{
'1':{
'itemDetails':{
'id'='1'
'prop1':'1',
'prop2':'2'
}
},
'0':{
'itemDetails':{
'id'='0'
'prop1':'1',
'prop2':'2'
},
'2':{
'itemDetails':{
'id'='1'
'prop1':'1',
'prop2':'2'
}
'other':{
'propA':'A',
'propB':'B'
}
}
}
the solution obviously does not work.
I use id, prop1 and prop2 to create objects.
What would be the best approach to automatically access itemDetails in the second case without writing json_file[‘document’][‘0’][‘itemDetails’] ?
If I understand correctly, you want to loop through all of
json_file['document']['0']['itemDetails'],json_file['document']['1']['itemDetails'], …If that’s the case, then:
Or, a one-liner:
item_details = {k: v['itemDetails'] for k, v in json_file['document']}Then, you would access them as
item_details['0'],item_details['1'], …Note: You can suppress the single quotes around 0 and 1, by using
int(key)orint(k).Edit:
If you want to access both cases seamlessly (whether there is one result or many), you could check:
Then loop through the
item_detailsdict.