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
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With