从带制表符的树形文本文件创建JSON对象
我有一个文本文件的例子:(我不知道这个叫什么,是树吗?)
key1
subkey1
subkey2
choice1
key2
subkey1
subkey2
我想让它看起来像这样:
[
{
"text":"key1",
"children":[
{
"text":"subkey1",
children:[]
},
{
"text":"subkey2",
children:[
{
"text":"choice1",
"children":[]
}
]
},
]
},
{
"text":"key2",
"children":[
{
"text":"subkey1",
children:[]
},
{
"text":"subkey2",
children:[]
},
]
}
]
我现在在做的事情是,我不太明白怎么把子元素放到父元素里面,而且这个结构应该可以无限深。
import itertools
def r(f, depth, parent, l, children):
for line in f:
line = line.rstrip()
newDepth = sum(1 for i in itertools.takewhile(lambda c: c=='\t', line))
node = line.strip()
if parent is not None:
print parent, children
children = [{"txt":node, "children":[]}]
# l.append({"txt":parent, "children":children})
r(f, newDepth, node, l, children)
json_list = []
r(open("test.txt"), 0, None, json_list, [])
print json_list
1 个回答
6
第一条规则,如果可以的话,尽量避免使用递归……在这里,你只需要知道祖先节点,而这些可以很简单地用一个列表来维护。注意,depth
0 是留给根节点的,第一层“用户”深度是 1
,所以在计算缩进时要加 +1
。
f = open("/tmp/test.txt", "r")
depth = 0
root = { "txt": "root", "children": [] }
parents = []
node = root
for line in f:
line = line.rstrip()
newDepth = len(line) - len(line.lstrip("\t")) + 1
print newDepth, line
# if the new depth is shallower than previous, we need to remove items from the list
if newDepth < depth:
parents = parents[:newDepth]
# if the new depth is deeper, we need to add our previous node
elif newDepth == depth + 1:
parents.append(node)
# levels skipped, not possible
elif newDepth > depth + 1:
raise Exception("Invalid file")
depth = newDepth
# create the new node
node = {"txt": line.strip(), "children":[]}
# add the new node into its parent's children
parents[-1]["children"].append(node)
json_list = root["children"]
print json_list