鉴于下面的 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)
...假设 data
是 json.loads(json_text)
或类似的结果,并且 section_id
是 int
(这是您在该示例 JSON 中获得的 ids)。
对于您的示例用法:
>>> get_path(data, 156)
u'Add Storage Devices, Guided Configuration, Configuration'
关于python - 从 JSON 创建层次结构路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17784218/