import json
text = '{"root":{"data":{"id":"ch58nhdpg680","created":1642147348460,"text":"Test"},"children":[{"data":{"id":"ch59laa5bfs0","created":1642149997389,"text":"Test1"},"children":[{"data":{"id":"ch58nhx203c0","created":1642147349630,"text":"Test2"},"children":[{"data":{"id":"ch58nk59rnc0","created":1642147354481,"text":"Test3"},"children":[]},{"data":{"id":"9fsviujkqng1","created":1642147354481,"text":"Test4"},"children":[]},{"data":{"id":"q04pd7vl5n6x","created":1642147354481,"text":"Test5"},"children":[]},{"data":{"id":"ds8zgx1avpke","created":1642147354481,"text":"Test6"},"children":[]},{"data":{"id":"nuy5ekj98l1o","created":1642147354481,"text":"Test7"},"children":[]}]},{"data":{"id":"ch59n8zmzjc0","created":1642150151305,"text":"Test8"},"children":[]}]},{"data":{"id":"ch59h6c42kg0","created":1642149675344,"text":"Test9"},"children":[]},{"data":{"id":"ch59lv8vf6o0","created":1642150043024,"text":"Test10"},"children":[]}]},"template":"default","theme":"fresh-blue","version":"1.4.43"}'
textJson = json.loads(text)
#### 获取某个节点的父节点
def get_chain_ids(tree_dict, target_id, depth=0):
cur_id = tree_dict["data"]["id"]
if cur_id == target_id:
yield cur_id
else:
yield_cur_id = False
for child_dict in tree_dict["children"]:
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 textJson["root"]["children"]:
# print("\nSearching tree (data: {:s})...".format(item["data"]["id"]))
ids = get_chain_ids(item, "ch59n8zmzjc0")
if (ids):
for item in ids:
print(item)
#### 获取某个节点的所有子节点,如果把get_child_id中的get_child_id(jsontext[key]["children"])注释掉,则只获取子节点,不包括子节点的子节点
child_ids = []
def get_child_id(jsontext):
for key in range(len(jsontext)):
child_ids.append(jsontext[key]["data"]["id"])
get_child_id(jsontext[key]["children"])
def get_child_ids(jsontext, target_id):
for key in range(len(jsontext)):
if jsontext[key]["data"]["id"] == target_id:
get_child_id(jsontext[key]["children"])
else:
get_child_ids(jsontext[key]["children"], target_id)
return child_ids
print(get_child_ids(textJson["root"]["children"], "ch58nhx203c0"))
获取百度脑图JSON数据某个节点的子节点或者父节点
最新推荐文章于 2024-04-19 22:51:48 发布