2016-08-03 27 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