使用json lib从Python嵌套JSON中获取元素


问题内容

我想使用“ 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']