python 根据父子信息 还原成json树

这篇博客介绍了如何使用Python从父子关系对中构建一棵树状JSON数据结构。通过定义Node和TreeProcessor类,实现了从关系列表到树形结构的转化,并提供了详细的代码实现。示例数据包括了节点的详细信息,如名称和别名,最终生成的JSON树展示了这些节点的层级关系。
摘要由CSDN通过智能技术生成
根据父子信息 还原成json树
需求

有一组数据 ([1,2], [2, 3], [1, 5], [5, 6]), 列表里的数据分别为父节点,子节点。将这组数据还原成树状json数据。

代码

定义一个Node对象

import json
from collections import defaultdict


class Node:
    def __init__(self, key, info):
        self.key = key
        self.info = info
        self.children = []

    def to_dict(self):
        result = dict()
        result["key"] = self.key

        for _k, _v in self.info.items():
            result[_k] = _v
        # 递归生成字典
        result["children"] = [x.to_dict() for x in self.children]
        return result
class TreeProcessor:
    def __init__(self, pair: list, info: dict, d_type="json"):
        """

        :param pair: [(0, 1), (0, 2)...] 父子关系对
        :param info: {0 : {"name": xxx}} 每个节点的详细信息
        :param d_type: 返回类型 json dict
        """
        self._pair = pair
        self._info = info
        self.d_type = d_type
        self.root_id, self._pair_map, self._ids = self._process_data()

    def _process_data(self):
        """
        将[(0, 1), (0, 2)...] 父子关系对
        变为 {father: [child, child]}
        :return:
        """
        pair_map = defaultdict(list)
        ids = set()
        fathers = set()
        children = set()
        for f, s in self._pair:
            ids.add(f)
            ids.add(s)
            fathers.add(f)
            children.add(s)
            pair_map[f].append(s)
        root_id = fathers - children
        root_id = list(root_id)[0] if root_id else None
        return root_id, pair_map, ids

    def _create_nodes(self):
        return {x: Node(x, self._info.get(x, {})) for x in self._ids}

    @property
    def tree(self):
        node_map = self._create_nodes()
        for k, v in self._pair_map.items():
            node_map[k].children = [node_map[i] for i in v]
        root_node: Node = node_map.get(self.root_id)

        tree_res = json.dumps(root_node.to_dict()) if self.d_type == 'json' else root_node.to_dict()
        return tree_res
结果
infos = {0: {"name": "zero", "alias": "ling"},
             1: {"name": "one", "alias": "yi"},
             2: {"name": "two", "alias": "er"},
             3: {"name": "three", "alias": "san"},
             4: {"name": "four", "alias": "si"},
             5: {"name": "five", "alias": "wu"},
             6: {"name": "six", "alias": "liu"},
             7: {"name": "seven", "alias": "qi"}}
relation = [(0, 1),
            (0, 2),
            (0, 3),
            (2, 4),
            (2, 5),
            (5, 6),
            (5, 7)]
tp = TreeProcessor(relation, infos)
tree_dict = tp.tree
print(tree_dict)
tree json
{
    "key": 0,
    "name": "zero",
    "alias": "ling",
    "children": [
        {
            "key": 1,
            "name": "one",
            "alias": "yi",
            "children": []
        },
        {
            "key": 2,
            "name": "two",
            "alias": "er",
            "children": [
                {
                    "key": 4,
                    "name": "four",
                    "alias": "si",
                    "children": []
                },
                {
                    "key": 5,
                    "name": "five",
                    "alias": "wu",
                    "children": [
                        {
                            "key": 6,
                            "name": "six",
                            "alias": "liu",
                            "children": []
                        },
                        {
                            "key": 7,
                            "name": "seven",
                            "alias": "qi",
                            "children": []
                        }
                    ]
                }
            ]
        },
        {
            "key": 3,
            "name": "three",
            "alias": "san",
            "children": []
        }
    ]
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuhengshi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值