获取百度脑图JSON数据某个节点的子节点或者父节点

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"))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值