我正在尝试为JSON对象构建层次结构树。
这是我到目前为止所拥有的:
nested_dict = lambda: defaultdict(nested_dict)
leaf = nested_dict()
root = {}
root["data"] = {"id": "Release"}
root["children"] = []
for (a, b, c, d) in zip(frame["a"], frame["b"], frame["c"], frame["d"]):
leaf[a][b][c] = d
for a in leaf:
root["children"].append({"data": {"id": a}})
print(root)
这对第一片叶子都很好,结果看起来像这样:
{
"data": {
"id": "Release"
},
"children": [
{
"data": {
"id": "content of a"
}
},
{
"data": {
"id": "content of a"
}
},
{
"data": {
"id": "content of a"
}
}
]
}
现在我想带孩子到a。 这是我的尝试:
nested_dict = lambda: defaultdict(nested_dict)
leaf = nested_dict()
root = {}
root["data"] = {"id": "Release"}
root["children"] = []
for (a, b, c, d) in zip(frame["a"], frame["b"], frame["c"], frame["d"]):
leaf[a][b][c] = d
for a in leaf:
root["children"].append({"data": {"id": a}})
for b in leaf[a]:
root["children"].append({"children": [{"data": {"id": b}}]})
print(root)
这是不想要的结果:
{
"data": {
"id": "Release"
},
"children": [
{
"data": {
"id": "content of a"
}
},
{
"children": [
{
"data": {
"id": "content of b"
}
}
]
},
{
"data": {
"id": "content of a"
}
},
{
"children": [
{
"data": {
"id": "content of b"
}
}
]
},
{
"children": [
{
"data": {
"id": "content of b"
}
}
]
},
{
"data": {
"id": "content of a"
}
},
{
"children": [
{
"data": {
"id": "content of b"
}
}
]
},
{
"children": [
{
"data": {
"id": "content of b"
}
}
]
}
]
}
我希望它看起来像这样:
{
"data": {
"id": "Release"
},
"children": [
{
"data": {
"id": "content of a"
},
"children": [
{
"data": {
"id": "content of b"
},
"children": [
{
"data": {
"id": "content of c"
}
}
]
},
{
"data": {
"id": "content of b"
},
"children": [
{
"data": {
"id": "content of c"
}
}
]
}
]
},
{
"data": {
"id": "Content of a"
},
"children": [
{
"data": {
"id": "content of b"
},
"children": [
{
"data": {
"id": "content of c"
}
},
{
"data": {
"id": "content of c"
}
},
{
"data": {
"id": "content of c"
}
}
]
},
{
"data": {
"id": "content of b"
},
"children": [
{
"data": {
"id": "content of c"
}
},
{
"data": {
"id": "content of c"
}
}
]
}
]
}
]
}
一整天都在工作,现在我是如此的嵌套,我找不到出路。