Get The Elements From Nested Json With Python Using Json Lib
I want to list all the elements from 'BoxDet' with the 'BoxDet' name. The aim is to list it that way: BoxDet : ABC ... A little part of my JSON: { 'id':1, 'name':'BoxH',
Solution 1:
You need a tree-search algorithm for this:
def locateByName(e,name):
if e.get('name',None) == name:
return e
for child in e.get('children',[]):
result = locateByName(child,name)
if result is not None:
return result
return None
Now you can use this recursive function to locate the element you want:
node = locateByName(output_json, 'BoxDet')
print node['name'],node['Ids']
Solution 2:
when you try to use a for loop on a dict, without any special consideration, you get only the keys out of the dict. That is:
>>> my_dict = {'foo': 'bar', 'baz':'quux'}
>>> list(my_dict)
['foo', 'baz']
>>> for x in my_dict:
... printrepr(x)
'foo''baz'
The most usual thing to do is to use dict.iteritems()
(just dict.items()
in python 3)
>>> for x in my_dict.iteritems():
... printrepr(x)
('foo', 'bar')
('baz', 'quux')
Or you can fetch the value for the key yourself:
>>> for x in my_dict:
... printrepr(x), repr(my_dict[x])
'foo''bar''baz''quux'
Solution 3:
If you want to iterate through the children of your entities you can do the following:
for children in output_json["children"]:
#Going down to ID: 100 levelfor grandchildren in children["children"]:
#Going down to ID: 1003 levelfor grandgrandchildren in grandchildren["children"]:
#Going down to ID: 1019 levelif grandgrandchildren["name"] == "BoxDet":
return"BoxDet" + " ".join(grandgrandchildren["Ids"])
Not that the data structure involved in the json module works more or less like classic dictionary where you access the value through the key:
my_dict[key] = value
Solution 4:
try it like this:
output_json = json.load(open('root.json'))
if"children"in output_json:
children = output_json["children"]
if"children"in children:
children1 = children["children"]
if"children"in children1:
children2 = children1["children"]
if"name"in children2:
name = children2["name"]
if"Ids"in children2:
ids = children2["Ids"]
print name, ids
Post a Comment for "Get The Elements From Nested Json With Python Using Json Lib"