2012-06-10 162 views
1

一個JSON樹結構我有一個數據文件,它看起來像這樣:建築物的標識符

ID attribute 
1 'text' 
101 'text' 
1011 'text' 
10111 'text' 
1011101 'text' 
1011102 'text' 
1011103 'text' 
1011104 'text' 
1011130 'text' 

我的目標是從這些數據建立JSON樹結構:

{ 
    [ 
    ID : 1, 
    attribute : 'text', 
    children : [ 
     ID: 101, 
     attribute : 'text', 
     children : [ 
      ... 
    ID : 2, 
     ... 
    ] 
} 

在Python中,我建立了這樣的字典列表:

[ {'id': ID, 'attr' : text}, {...} ] 

我想我可以使用的事實,葉ID包含他的父母身份證,但我看不到建立我想要的結構的方式。

我將不勝感激任何幫助,在僞代碼或任何其他編程語言。

+0

我想你會遇到麻煩,無論如何,如果還有更多的99頂級樹。 – TankorSmash

回答

0

解決方案几乎沒有變化工作:

# open & read raw file 
f=open(args[0], 'r') 
text = f.read() 

# 
text = map(lambda s: s.split(" ", 1), text.strip().replace("'","").splitlines()) 
tree = [{'prefix': '', 'children':[]}] 
stack = [tree[0]] 

for id, attr in text: 
    while not id.startswith(stack[-1]['prefix']): 
     stack.pop() 
    node = {'prefix': id, 'attr': attr, 'children': []} 
    stack[-1]['children'].append(node) 
    stack.append(node) 

pprint.pprint(tree) 

print json.dumps(tree) 
f=open(args[1], 'w') 
f.write(json.dumps(tree, sort_keys=True, indent=1)) 

謝謝!

3

我沒有完全得到您的ID編號系統,所以這裏是一個簡單的前綴樹碼:從thg435

ls = """ 
1 'text' 
101 'text' 
1011 'text' 
10111 'text' 
1011101 'text' 
2 two 
2111 'text' 
21114 'text' 
25 'text' 
2567 'text' 
""" 
ls = map(str.split, ls.strip().splitlines()) 


tree = [{'prefix': '', 'children':[]}] 
stack = [tree[0]] 

for id, attr in ls: 
    while not id.startswith(stack[-1]['prefix']): 
     stack.pop() 
    node = {'prefix': id, 'attr': attr, 'children': []} 
    stack[-1]['children'].append(node) 
    stack.append(node) 

import pprint 
pprint.pprint(tree) 
+0

+1。在那裏扔一些解釋,我們有一個燉。 – TankorSmash