Reputation: 145
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",
"readOnly":true,
"children":[
{
"id":100,
"name":"Box1",
"readOnly":true,
"children":[
{
"id":1003,
"name":"Box2",
"children":[
{
"id":1019,
"name":"BoxDet",
"Ids":[
"ABC",
"ABC2",
"DEF2",
"DEFHD",
"LKK"
]
}
]
}
]
}
]
}
My problem is just on the beginning, I just cannot go deeper as first { }. My code...
output_json = json.load(open('root.json'))
for first in output_json:
print first
for second in first:
print second
... returns me something like that:
readOnly
r
e
a
d
O
n
l
y
children
c
h
i
l
d
r
e
n
... an so on. I can't really even go deeper to Box1, not even mentioning Box2. I'm working with Python 2.7
Upvotes: 4
Views: 20562
Reputation: 328594
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']
Upvotes: 10
Reputation: 3857
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 level
for grandchildren in children["children"]:
#Going down to ID: 1003 level
for grandgrandchildren in grandchildren["children"]:
#Going down to ID: 1019 level
if 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
Upvotes: 1
Reputation: 15679
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
Upvotes: 0
Reputation: 156158
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:
... print repr(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():
... print repr(x)
('foo', 'bar')
('baz', 'quux')
Or you can fetch the value for the key yourself:
>>> for x in my_dict:
... print repr(x), repr(my_dict[x])
'foo' 'bar'
'baz' 'quux'
Upvotes: 1