我有一个最小生成树算法创建了以下数据:创建JSON树未知根
links = [("Earl","Bob"),("Bob","Sam"),("Bob","Leroy"),("Leroy","Harry")]
我需要将数据转换成以下JSON树:
{
"id": "Earl",
"name": "Earl",
"children": [
{
"id": "Bob",
"name": "Bob",
"children": [
{
"id": "Leroy",
"name": "Leroy",
"children": [
{
"id": "Harry",
"name": "Harry"
}
]
},
{
"id": "Sam",
"name": "Sam"
}
]
}
]
}
我有下面的脚本除了在树上添加了一个名为'Root'的根节点,我不想要:
import json
links = [("Earl","Bob"),("Bob","Sam"),("Bob","Leroy"),("Leroy","Harry")]
parents, children = zip(*links)
root_nodes = {x for x in parents if x not in children}
for node in root_nodes:
links.append(('Root', node))
def get_nodes(node):
d = {}
d['id'] = node
d['name'] = node
children = get_children(node)
if children:
d['children'] = [get_nodes(child) for child in children]
return d
def get_children(node):
return [x[1] for x in links if x[0] == node]
tree = get_nodes('Root')
print(json.dumps(tree, indent=2))
### output below ###
{
"children": [
{
"children": [
{
"children": [
{
"id": "Sam",
"name": "Sam"
},
{
"children": [
{
"id": "Harry",
"name": "Harry"
}
],
"id": "Leroy",
"name": "Leroy"
}
],
"id": "Bob",
"name": "Bob"
}
],
"id": "Earl",
"name": "Earl"
}
],
"id": "Root",
"name": "Root"
}
我需要的是不要添加假“根”作为根节点。根应该只是links
中没有父节点的任何现有节点(按照第一个json示例)。换句话说,树的根不一定是伯爵,它可以是任何没有父母的节点。树可以从那里开始扩展。
也许有更好的算法来做到这一点,而不是试图修改这个?
tree = tree.children [0]结果为:AttributeError:'dict'对象没有属性'children' – darkpool
对不起,忘记了python语法了一下。 'tree = tree.get(“children”)[0]' – exec