python - 从 JSON 创建层次结构路径

标签 python json

鉴于下面的 JSON,为给定“id”创建“名称”分层列表的最佳方法是什么?层次结构中可以有任意数量的部分。

例如,提供 ID“156”将返回“添加存储设备、引导配置、配置”

我一直在考虑使用 iteritems(),但需要一些帮助。

 {
    "result": true,
    "sections": [
        {
            "depth": 0,
            "display_order": 1,
            "id": 154,
            "name": "Configuration",
            "parent_id": null,
            "suite_id": 5
        },
        {
            "depth": 1,
            "display_order": 2,
            "id": 155,
            "name": "Guided Configuration",
            "parent_id": 154,
            "suite_id": 5
        },
        {
            "depth": 2,
            "display_order": 3,
            "id": 156,
            "name": "Add Storage Devices",
            "parent_id": 155,
            "suite_id": 5
        },
        {
            "depth": 0,
            "display_order": 4,
            "id": 160,
            "name": "NEW",
            "parent_id": null,
            "suite_id": 5
        },
        {
            "depth": 1,
            "display_order": 5,
            "id": 161,
            "name": "NEWS",
            "parent_id": 160,
            "suite_id": 5
        }
    ]
}

最佳答案

这是一种方法:

def get_path(data, section_id):
    path = []
    while section_id is not None:
        section = next(s for s in data["sections"] if s["id"] == section_id)
        path.append(section["name"])
        section_id = section["parent_id"]
    return ", ".join(path)

...假设 datajson.loads(json_text) 或类似的结果,并且 section_idint(这是您在该示例 JSON 中获得的 ids)。

对于您的示例用法:

>>> get_path(data, 156)
u'Add Storage Devices, Guided Configuration, Configuration'

关于python - 从 JSON 创建层次结构路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17784218/

相关文章:

json - 如何在Elasticsearch中将xml存储为字段?

c# - 在 C# 中使用索引数组反序列化 JSON

python - 拖放什么都不做

python - 如何在 Pandas 数据框列中选择一系列值?

Python docx row.cells 多次返回 "merged"单元格

python - SSL:来自 Ubuntu 16.0.4 中的 Python pip 的 CERTIFICATE_VERIFY_FAILED 错误

c# - 使用 DataContractJsonSerializer 创建非 XML Json 文件

java - jQuery AJAX 调用 Spring Controller 时出现 404 not found 错误

javascript - 从 google apps 脚本上的 json 发布到 facebook

python - 编写并行循环