使用json lib从Python嵌套JSON中获取元素
问题描述:
我想用"BoxDet"名称列出"BoxDet"中的所有元素.目的是这样列出:BoxDet:ABC ...
I want to list all the elements from "BoxDet" with the "BoxDet" name. The aim is to list it that way: BoxDet : ABC ...
我的JSON的一小部分:
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
...等等.我什至不能更深入地了解Box1,甚至不提Box2.我正在使用Python 2.7
... 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']