[英]python json accessing an id in a nested dictionary and list based on it's value
[英]json list to nested based on id
如何按 id 對 JSON 對象進行分組,以在 Python 中創建嵌套的 JSON? JSON 的結構如下:
[{
"id": "4",
"title": "Part 4",
"children": {}
},{
"id": "4.1.",
"title": "Section 4.1. Transition Rule",
"children": {}
},
{
"id": "4.1.1.",
"title": "4.1.1. Transition, January 2014",
"children": {}
},
{
"id": "4.1.1.1.",
"title": "4.1.1.1. Transition Rule",
"children": {}
},
{
"id": "4.1.2.",
"title": "4.1.2. Transition, January 2015",
"children": {}
},
{
"id": "4.1.2.1.",
"title": "4.1.2.1. Transition Rule",
"children": {}
},
]]
目標是擁有一個樹結構,其中每個對象(部分)包含從 4 到 4.1 > 4.1.1 > 4.1.1.1 的所有子部分。
所需 output 的片段如下:
[
{
"id":"4",
"title":"Part 4",
"children":{
{
"id":"4.1.",
"title":"Section 4.1. Transition Rule",
"children":{
{
"id":"4.1.1.",
"title":"4.1.1. Transition, January 2014",
"children":{
{
"id":"4.1.1.1.",
"title":"4.1.1.1. Transition Rule",
"children":{
}
}
}
},
{
"id":"4.1.2.",
"title":"4.1.2. Transition, January 2015",
"children":{
{
"id":"4.1.2.1.",
"title":"4.1.2.1. Transition Rule",
"children":{
您可以使用遞歸:
from collections import defaultdict
def get_tree(d):
_d, r = defaultdict(list), []
for i in d:
_d[i['key'][0]].append({**i, 'key':i['key'][1:]})
for b in _d.values():
j, k = [l for l in b if not l['key']], [l for l in b if l['key']]
if j:
r.extend([{**{x:y for x, y in i.items() if x != 'key'}, 'children':get_tree(k)} for i in j])
else:
r.extend(get_tree(k))
return r
data = [{'id': '4', 'title': 'Part 4', 'children': {}}, {'id': '4.1.', 'title': 'Section 4.1. Transition Rule', 'children': {}}, {'id': '4.1.1.', 'title': '4.1.1. Transition, January 2014', 'children': {}}, {'id': '4.1.1.1.', 'title': '4.1.1.1. Transition Rule', 'children': {}}, {'id': '4.1.2.', 'title': '4.1.2. Transition, January 2015', 'children': {}}, {'id': '4.1.2.1.', 'title': '4.1.2.1. Transition Rule', 'children': {}}, {'id': '4.1.3.', 'title': '4.1.3. Transition, January 2017', 'children': {}}]
import json
print(json.dumps(get_tree([{**i, 'key':[*filter(None, i['id'].split('.'))]} for i in data]), indent=4))
Output:
[
{
"id": "4",
"title": "Part 4",
"children": [
{
"id": "4.1.",
"title": "Section 4.1. Transition Rule",
"children": [
{
"id": "4.1.1.",
"title": "4.1.1. Transition, January 2014",
"children": [
{
"id": "4.1.1.1.",
"title": "4.1.1.1. Transition Rule",
"children": []
}
]
},
{
"id": "4.1.2.",
"title": "4.1.2. Transition, January 2015",
"children": [
{
"id": "4.1.2.1.",
"title": "4.1.2.1. Transition Rule",
"children": []
}
]
},
{
"id": "4.1.3.",
"title": "4.1.3. Transition, January 2017",
"children": []
}
]
}
]
}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.