我有一个文本文件的例子:(我不知道你怎么称呼它,一棵树?)

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

最佳答案

第一条规则,如果可以的话,避免递归......这里你只需要知道祖先,它们可以很容易地在一个列表中维护。请注意,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

关于python - 从选项卡式树文本文件创建 JSON 对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25170715/

10-15 17:37