2012-06-10 63 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