【问题标题】:How to convert json to tree in python如何在python中将json转换为树
【发布时间】:2023-03-29 03:26:01
【问题描述】:

我有一个如下的 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 获取此路径吗?

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

任何帮助都将是可观的。

【问题讨论】:

  • This SO 帖子可以帮助您。

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


【解决方案1】:

您想生成一个字符串列表,表示通过"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() 中。

【讨论】:

  • 嗨,你可以在这里添加深度吗?
  • 你到底是什么意思,@DanialShabbir?每条路径的深度只是在路径分隔符上分割路径时的元素数?还是说其他深度?
  • 是的,明白了。感谢您的回复。
猜你喜欢
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 2019-10-29
  • 1970-01-01
  • 2020-12-19
  • 2016-11-05
  • 2013-03-01
  • 2019-05-28
相关资源
最近更新 更多