我有以下代码在列表列表中生成父子关系
Levels=[['L1','L1','L2'],
['L1','L1','L3'],
['L1','L2'],
['L2','L2','L3'],
['L2','L2','L1'],
['L3','L2'],
['L4','L2','L1'],
['L4','L2','L4']]
def append_path(root, paths):
if paths:
child = root.setdefault(paths[0], {})
append_path(child, paths[1:])
for p in Levels:
append_path(root, p)
# Print results
import json
print(json.dumps(root, indent=4))
生成的输出采用以下格式
{
"L1": {
"L1": {
"L2": {},
"L3": {}
},
"L2": {}
},
"L2": {
"L2": {
"L3": {},
"L1": {}
}
},
"L3": {
"L2": {}
},
"L4": {
"L2": {
"L1": {},
"L4": {}
}
}
}
我想将其转换为jquery可视化所需的以下格式。
"name": "L1",
"children": [
{
"name": "L1",
"children":[
{
"name":"L3",
"children":[{}]
},
{
"name":"L1",
"children":[{}]
}]
},
{
"name":"L2",
"children":[{}]
}
]
以此类推
答案 0 :(得分:3)
您可以递归地执行此操作(以问题中发布的格式构建root
后):
def convert(d):
return [{'name': k, 'children': convert(v) if v else [{}]} for k, v in d.items()]
print(json.dumps(convert(root), indent=2))
输出
[
{
"children": [
{
"children": [
{
"children": [
{}
],
"name": "L3"
},
{
"children": [
{}
],
"name": "L1"
}
],
"name": "L2"
}
],
"name": "L2"
},
{
"children": [
{
"children": [
{}
],
"name": "L2"
}
],
"name": "L3"
},
{
"children": [
{
"children": [
{
"children": [
{}
],
"name": "L4"
},
{
"children": [
{}
],
"name": "L1"
}
],
"name": "L2"
}
],
"name": "L4"
},
{
"children": [
{
"children": [
{}
],
"name": "L2"
},
{
"children": [
{
"children": [
{}
],
"name": "L2"
},
{
"children": [
{}
],
"name": "L3"
}
],
"name": "L1"
}
],
"name": "L1"
}
]