gpt4 book ai didi

python - JSON 打印从根到叶的所有路径

转载 作者:行者123 更新时间:2023-12-02 02:21:48 25 4
gpt4 key购买 nike

[
{
"name": "Basic",
"id": "home",
"childrens": [
{
"name": "Dashboard",
"viewtype": "custom",
"view": "dashboard.html",
"childrens": []
},
{
"name": "DeviceInfo",
"href": "WSettings",
"childrens": [
{
"name": "DeviceInfo Form",
"childrens": [
{
"name": "DeviceInfo Form1",
"viewtype": "xml",
"view": "dinfo",
"childrens": []
},
{
"name": "DeviceInfo Form2",
"viewtype": "xml",
"view": "complexjson",
"childrens": []
}
]
},
{
"name": "DeviceInfo Table",
"childrens": [
{
"name": "DeviceInfo Table1",
"viewtype": "xml",
"view": "dinfotable",
"childrens": []
},
{
"name": "DeviceInfo Table2",
"viewtype": "xml",
"view": "jsontable",
"childrens": []
}
]
}

]
},
{
"name": "Hybrid",
"childrens": [
{
"name": "Table-Form",
"viewtype": "xml",
"view": "hybrid",
"childrens": []
}
]
}
]
},
{
"name": "Advanced",
"id": "profile",
"childrens": []
}
]

想要打印从根到叶的所有路径(带有空的'childrens')。 例如Basic.DeviceInfo.DeviceInfo Form.DeviceInfo Form1

一切都很顺利,直到DeviceInfo Form2

说到DeviceInfo TableDeviceInfo Form就出现了 --> Basic.DeviceInfo.DeviceInfo Form.DeviceInfo Table.DeviceInfo Table1。

这不应该发生。相反,我需要 Basic.DeviceInfo.DeviceInfo Table.DeviceInfo Table1。

我的代码哪里出了问题。有什么解决办法吗?

def walk(list1, path = ""):
for dic in list1:
#print('about to walk', dic['name'], 'passing path -->', path)
if(len(dic['childrens']) == 0):
print('leaf --->', path+dic['name']+'.')
else:
path = path+dic['name']+'.'
#passing parent name to childreni
walk(dic['childrens'], path)

最佳答案

您正在 else 子句中设置 path = path +dic['name']+'.' 。一旦 walk() 函数完成对 DeviceInfoForm“childrens”的遍历,它就会尝试遍历 DeviceInfoTable。但是,您的函数已经设置了路径Basic.DeviceInfo.DeviceInfoForm。

您需要重新组织函数,以便不在 else: 语句中设置路径。也许

else:
walk(dic['childrens'], path+dic['name']+'.')

这样您就可以将正确的路径传递给函数,但不会显式设置它。

关于python - JSON 打印从根到叶的所有路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28571858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com