有如下的json。
{
{
"id": 1,
"child": [
{
"id": 4,
"child": [],
},
{
"id": 2,
"child": [
{
"id": 37,
"child": [],
},
{
"id": 39,
"child": [],
}
]
},
{
"id": 3,
"child": [],
},
]
},
{
"id": 120,
"child": [],
},
{
"id": 121,
"child": [
{
"id": 122,
"child": [],
}
]
}
}
例如,如果你想获得id为37的元素的父元素的id,你会怎么做?
在这种情况下,我们想要列入[1, 2]
等列表
我认为我们应该如下递归处理,但我不知道如何在id匹配时获取父元素。
def get_parent(self, json_tree, target_id):
for element in json_tree:
if element['id'] == target_id:
????
else:
if element['child']:
self.get_routes_tree(element['child'],
target_id)
答案 0 :(得分:1)
如果您希望用于到达底部id
的节点列表,您可以使用以下内容:
def get_parent(json_tree, target_id):
for element in json_tree:
if element['id'] == target_id:
return [element['id']]
else:
if element['child']:
check_child = get_parent(element['child'], target_id)
if check_child:
return [element['id']] + check_child
这会在id
匹配时创建一个列表,然后在循环中向上传递时,会将每个级别的id
添加到列表的前面。
所以,纠正你的json是正确的(没有尾随逗号)并调用函数:
js = json.loads('[{"id": 1,"child": [{"id": 4,"child": []},{"id": 2,"child": [{"id": 37,"child": []},{"id": 39,"child": []}]},{"id": 3,"child": []}]},{"id": 120,"child": []},{"id": 121,"child": [{"id": 122,"child": []}]}]')
print(get_parent(js, 37))
打印
[1, 2, 37]
答案 1 :(得分:0)
code.py :
import sys
TREE = [
{
"id": 1,
"child": [
{
"id": 4,
"child": [],
},
{
"id": 2,
"child": [
{
"id": 37,
"child": [],
},
{
"id": 39,
"child": [],
}
]
},
{
"id": 3,
"child": [],
},
]
},
{
"id": 120,
"child": [],
},
{
"id": 121,
"child": [
{
"id": 122,
"child": [],
}
]
}
]
def get_chain_ids(tree_dict, target_id, depth=0):
cur_id = tree_dict["id"]
if cur_id == target_id:
yield cur_id
else:
yield_cur_id = False
for child_dict in tree_dict["child"]:
for child_id in get_chain_ids(child_dict, target_id, depth=depth + 1):
yield_cur_id = True
yield child_id
if yield_cur_id:
yield cur_id
if __name__ == "__main__":
print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
for item in TREE:
print("\nSearching tree (id: {:d})...".format(item["id"]))
ids = get_chain_ids(item, 37)
if (ids):
for item in ids:
print(item)
备注强>:
TEXT
dict )不正确,我不得不调整它(除了格式化)get_chain_ids
获取树 root (tree_dict
)这是一个字典,target_id
作为参数,并返回一个生成所有节点id的生成器target_id
到根ID depth
目前尚未使用TREE
是list
个节点,我不得不迭代它并将每个元素传递给函数"id"
或"child"
个密钥,或者其值不符合预期)的情况。<强>输出强>:
(py35x64_test) E:\Work\Dev\StackOverflow\q048865303>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code.py Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32 Searching tree (id: 1)... 37 2 1 Searching tree (id: 120)... Searching tree (id: 121)...