[英]Loop through a nested dictionary and get its path
I have a JSON object with the following structure:我有一个 JSON object 具有以下结构:
source = {
"org_name": "root",
"orgs": [
{
"org_name": "alpha1",
"orgs": []
},
{
"org_name": "alpha2",
"orgs": [
{
"org_name": "beta1",
"orgs": [
{
"org_name": "gama1",
"orgs": []
}
]
}
]
}
]
} }
I want to parse this JSON and add a key named org_path which contains the path of the orgs the output should be like this我想解析这个 JSON 并添加一个名为 org_path 的键,其中包含 orgs 的路径 output 应该是这样的
source = {
"org_name": "root",
"org_path": "root"
"orgs": [
{
"org_name": "alpha1",
"org_path": "root/alpha1"
"orgs": []
},
{
"org_name": "alpha2",
"org_path": "root/alpha2"
"orgs": [
{
"org_name": "beta1",
"org_path": "root/alpha2/beta1"
"orgs": [
{
"org_name": "gama1",
"org_path": "root/alpha2/gama1"
"orgs": []
}
]
}
]
}
]
}
I am having a hard time finding a logic to get a output.我很难找到获得 output 的逻辑。
Here is a solution这是一个解决方案
def add_path_to_dict(dictionary, path=""):
path += dictionary["org_name"]
dictionary["org_path"] = path
path +="/"
for orgs in dictionary["orgs"]:
orgs = add_path_to_dict(orgs, path)
return dictionary
if __name__ == "__main__":
print(add_path_to_dict(source))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.