我有一个像下面这样的清单。第一列是父级,第二列是子级,第三列是节点属性。我需要将以下内容转换为JSON格式,如下所示。
0 0 "flair" 1000
0 1 "analytics" 1000
1 2 "cluster" 1000
2 3 "AgglomerativeCluster" 1000
2 4 "CommunityStructure" 1000
1 5 "Graph" 1000
5 6 "BetweennessCentrality" 1000
5 7 "LinkDistance"
pc = []
pc.append([0, 0 ,"flair", 1000])
pc.append([0,1, "analytics", 1000])
pc.append([1, 2, "cluster", 1000])
pc.append([2 ,3, "AgglomerativeCluster", 1000])
pc.append([2 ,4, "CommunityStructure" ,1000])
pc.append([1 ,5, "Graph", 1000])
pc.append([5, 6, "BetweennessCentrality", 1000])
pc.append([5, 7, "LinkDistance",1000])
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{"name": "AgglomerativeCluster", "size": 3938},
{"name": "CommunityStructure", "size": 3812},
]
},
{
"name": "graph",
"children": [
{"name": "BetweennessCentrality", "size": 3534},
{"name": "LinkDistance", "size": 5731}
]
}
]
}
]
}
最佳答案
对您的输入进行一些更改,对于根节点“ flair”,我使用“ -1”作为其父ID而不是“ 0”。
import json
pc = []
pc.append([-1, 0 ,"flair", 1000])
pc.append([0,1, "analytics", 1000])
pc.append([1, 2, "cluster", 1000])
pc.append([2 ,3, "AgglomerativeCluster", 1000])
pc.append([2 ,4, "CommunityStructure" ,1000])
pc.append([1 ,5, "Graph", 1000])
pc.append([5, 6, "BetweennessCentrality", 1000])
pc.append([5, 7, "LinkDistance",1000])
def listToDict(input):
root = {}
lookup = {}
for parent_id, id, name, attr in input:
if parent_id == -1:
root['name'] = name;
lookup[id] = root
else:
node = {'name': name}
lookup[parent_id].setdefault('children', []).append(node)
lookup[id] = node
return root
result = listToDict(pc)
print result
print json.dumps(result)