python - 使用 json lib 通过 Python 从嵌套的 JSON 中获取元素

标签 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']

关于python - 使用 json lib 通过 Python 从嵌套的 JSON 中获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18830955/

相关文章:

python - 确定从 spacy 中提取的文本是否是一个完整的句子

python - 为所有用户安装 Anaconda 并访问 python

html - 我们可以通过JSONX发送html代码以获取它在JSON中吗

jQuery AJAX GET/POST 请求在错误处理程序中返回 404,但从服务器发送有效响应

python - Jupyter 在 Mac 上安装失败

python - 如何在 jenkins 构建中激活 conda 环境

python - 获取错误/usr/bin/env : node : Permission Denied

c++ - rapidjson - 更改对象 - 添加元素/项目

php - Xcode 7 beta swift 使用未解析的标识符

json - Youtube API - 通过 Json 获取 youtube 趋势,可能吗?