2016-08-03 43 views
0

我有一个最小生成树算法创建了以下数据:创建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示例)。换句话说,树的根不一定是伯爵,它可以是任何没有父母的节点。树可以从那里开始扩展。

也许有更好的算法来做到这一点,而不是试图修改这个?

回答

-1
tree = get_nodes('Root'); 
tree = tree.children[0]; 
print(json.dumps(tree, indent=2)); 
+0

tree = tree.children [0]结果为:AttributeError:'dict'对象没有属性'children' – darkpool

+0

对不起,忘记了python语法了一下。 'tree = tree.get(“children”)[0]' – exec

-1

这不是因为您已经添加了伯爵作为Root的孩子吗?附:

links.append(('Root', node)) 
print links # [('Earl', 'Bob'), ('Bob', 'Sam'), ('Bob', 'Leroy'), ('Leroy', 'Harry'), ('Root', 'Earl')] 

当您运行children = get_children(node)node = 'Root'所以,现在,你会得到True

+0

是的,这是问题。但是,我不知道如何做到这一点,以便没有“根”作为根节点。根需要是没有父节点的任何节点。我只是以伯爵为例。有关如何去做这件事的任何建议? – darkpool

+0

你能得到子节点的内容吗?就像'print(json.dumps(tree ['children'],indent = 2))'? – Frangipanes