我想列出名称为“BoxDet”的“BoxDet”中的所有元素。目的是这样列出:BoxDet : ABC ...
我的 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"
]
}
]
}
]
}
]
}
我的问题才刚刚开始,我无法像第一个{}那样深入。 我的代码...
output_json = json.load(open('root.json'))
for first in output_json:
print first
for second in first:
print second
...返回给我类似的东西:
readOnly
r
e
a
d
O
n
l
y
children
c
h
i
l
d
r
e
n
...等等。我什至无法深入了解 Box1,更不用说 Box2 了。我正在使用 Python 2.7
最佳答案
为此你需要一个树搜索算法:
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
现在您可以使用这个递归函数来定位您想要的元素:
node = locateByName(output_json, 'BoxDet')
print node['name'],node['Ids']
关于python - 使用 json lib 通过 Python 从嵌套的 JSON 中获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18830955/