简体   繁体   English

如何在python中将json转换为树

[英]How to convert json to tree in python

I have a json file like below:我有一个如下的 json 文件:

{
    "App Builder": {
        "utterance": [
            "create an app",
            "create app for me",
            "can you create an application?"
        ],
        "question": [
            "Do you want to create application through UI or API Builder?",
            "Do you want to try our getting started page?"
        ],
        "children": [{
                "API Builder": {
                    "utterance": [
                        "create an app using API Buider",
                        "make an application using API Builder",
                        "create API Builder application"
                    ]
                }
            },
            {
                "UI": {
                    "utterance": [
                        "create an app using user interface",
                        "make an application using UI",
                        "create UI application"
                    ],
                    "question": [
                            "Do you want to create application through Template or UI Builder?",
                            "Do you want to try our getting started page?"
                        ]

                        ,
                    "children": [{
                            "UI Builder": {
                                "utterance": [
                                    "create an app using UI Buider",
                                    "make an application using UI Builder",
                                    "create UI Builder application"
                                ]
                            }
                        },
                        {
                            "Template": {
                                "utterance": [
                                    "create an app using Template",
                                    "make an application using Template",
                                    "create Template application"
                                ],
                                "question": [
                                    "Do you want to create application through Angular or React or PHP?",
                                    "Do you want to try our getting started page?"
                                ],
                                "children": [{
                                    "Angular": {
                                        "utterance": [
                                            "create an app using Angular",
                                            "make an application using Angular template",
                                            "create Angular application"
                                        ]
                                    }
                                }, {
                                    "React": {
                                        "utterance": [
                                            "create an app using React",
                                            "make an application using template React",
                                            "create React application"
                                        ]
                                    }
                                }, {
                                    "PHP": {
                                        "utterance": [
                                            "create an app using PHP",
                                            "make an application using template PHP",
                                            "create PHP application"
                                        ]
                                    }
                                }]
                            }
                        }
                    ]
                }
            }
        ]
    }
}

From this, I want to find all walks of each node.由此,我想找到每个节点的所有行。 By using the following code, I somehow managed to get the result given below.通过使用下面的代码,我设法得到了下面给出的结果。

edges = []
leaves = []
nodes = []
def get_edges(treedict, parent=None):
    try:
        name = next(iter(treedict.keys()))
        nodes.append(name)
        if parent is not None:
            edges.append((parent, name))
        for item in treedict[name]["children"]:
            if isinstance(item, dict):
                get_edges(item, parent=name)
            else:
                edges.append((name, item))

    except KeyError as e:
        leaves.append(name)
        pass

Intermediate result:中间结果:

print(edges)

[('App Builder', 'API Builder'), ('App Builder', 'UI'), ('UI', 'UI Builder'), ('UI', 'Template'), ('Template', 'Angular'), ('Template', 'React'), ('Template', 'PHP')]

Now I want to find the path of each nodes.现在我想找到每个节点的路径。 ie, IE,

['App Builder', 'App Builder/API Builder', 'App Builder/UI', 'App Builder/UI/UI Builder', 'App Builder/UI/Template',
         'App Builder/UI/Template/Angular', 'App Builder/UI/Template/React', 'App Builder/UI/Template/PHP']

How can I get these values?我怎样才能得到这些值?

Can I get this path from edges only by converting the list into tree?我只能通过将列表转换为树来从edges获取这条路径吗?

Any other better approach for this problem?对于这个问题还有其他更好的方法吗?

any help would be appreciable.任何帮助都将是可观的。

You want to generate a list of strings, that represent the path to each node connected through "children" to other nodes, with the path being made up of the keys of the nodes.您想要生成一个字符串列表,表示通过"children"连接到其他节点的每个节点的路径,路径由节点的键组成。

import json


def paths(data):
    for key, value in data.items():
        yield key
        if 'children' in value:
            for child in value['children']:
                for path in paths(child):
                    yield f'{key}/{path}'


with open('your_data.json') as f:
    print(list(paths(json.load(f))))

Note that paths() is a generator, yielding one result at a time, which is why the result of paths() is wrapped in list() before printing the result.请注意, paths()是一个生成器,一次产生一个结果,这就是为什么在打印结果之前将paths()的结果包装在list()中的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM