python - 如何在python中将json转换为树

标签 python json python-3.x python-2.7 tree

我有一个如下所示的 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"
                                        ]
                                    }
                                }]
                            }
                        }
                    ]
                }
            }
        ]
    }
}

由此,我想找到每个节点的所有路径。通过使用以下代码,我以某种方式设法获得了下面给出的结果。

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

中间结果:

print(edges)

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

现在我想找到每个节点的路径。即,

['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']

如何获取这些值?

我可以仅通过将列表转换为树来从edges获取这条路径吗?

还有其他更好的方法来解决这个问题吗?

任何帮助将不胜感激。

最佳答案

您想要生成一个字符串列表,该列表表示通过“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))))

请注意,paths() 是一个生成器,一次生成一个结果,这就是为什么 paths() 的结果被包装在 list( ) 在打印结果之前。

关于python - 如何在python中将json转换为树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57685165/

相关文章:

python - 如何使用python增加grpc中的消息大小

javascript - 查找给定范围内的当天

c# - 解析 JSON 时将未定义的数据成员名称放入通用 Diction<string, object> 中

c# - 使用 JSON.net 和 .net WebApi 反序列化 TimeSpan

python - 没有numpy的矩阵转置,错误: list index out of range

python-3.x - 在使用 dictconfig 的 python3 日志记录设置中记录异常时如何格式化错误消息和堆栈?

python - 在 python 中提交后是否可以回滚 sqlite3 更改

Python - ctypes - 如何调用函数和访问结构字段?

python - 如何将分隔值转换为one-hot编码列?

python - wxPython - 将项目保存在 ListCtrl 中