无限极分类

2021-05-25  本文已影响0人  垃圾桶边的狗
import json

def generate_tree(source, parent):

    tree = []

    for item in source:

        if item["parent"] == parent:

            item["child"] = generate_tree(source, item["id"])

            tree.append(item)

    return tree

if __name__ == '__main__':
    permission_source = [
    {"id": 1, "name": '电器', "parent": 0},
    {"id": 2, "name": '水果', "parent": 0},
    {"id": 3, "name": '家用电器', "parent": 1},
    {"id": 4, "name": '电吹风', "parent": 3},
    {"id": 5, "name": '电风扇', "parent": 3},
    {"id": 6, "name": '台灯', "parent": 3},
    {"id": 7, "name": '商用电器', "parent": 1},
    {"id": 9, "name": '苹果', "parent": 2},
    {"id": 10, "name": '大苹果', "parent": 9},
    {"id": 11, "name": '小苹果', "parent": 9},
    {"id": 12, "name": '打印机', "parent": 7},

    ]

    permission_tree = generate_tree(permission_source, 0)

    print(json.dumps(permission_tree, ensure_ascii=False,indent=4))

result
[
    {
        "id": 1,       
        "name": "电器",
        "parent": 0,   
        "child": [
            {
                "id": 3,
                "name": "家用电器",
                "parent": 1,
                "child": [
                    {
                        "id": 4,
                        "name": "电吹风",
                        "parent": 3,
                        "child": []
                    },
                    {
                        "id": 5,
                        "name": "电风扇",
                        "parent": 3,
                        "child": []
                    },
                    {
                        "id": 6,
                        "name": "台灯",
                        "parent": 3,
                        "child": []
                    }
                ]
            },
            {
                "id": 7,
                "name": "商用电器",
                "parent": 1,
                "child": [
                    {
                        "id": 12,
                        "name": "打印机",
                        "parent": 7,
                        "child": []
                    }
                ]
            }
        ]
    },
    {
        "id": 2,
        "name": "水果",
        "parent": 0,
        "child": [
            {
                "id": 9,
                "name": "苹果",
                "parent": 2,
                "child": [
                    {
                        "id": 10,
                        "name": "大苹果",
                        "parent": 9,
                        "child": []
                    },
                    {
                        "id": 11,
                        "name": "小苹果",
                        "parent": 9,
                        "child": []
                    }
                ]
            }
        ]
    }
]
上一篇 下一篇

猜你喜欢

热点阅读