使用json lib从Python嵌套JSON中获取元素 [英] Get the elements from nested JSON with Python using json lib

查看:173
本文介绍了使用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']

这篇关于使用json lib从Python嵌套JSON中获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆