如何将文本转换为"nested"字典?



我正在尝试将缩进文本转换为python中嵌套字典的列表从python的缩进文本文件中创建一个树/深度嵌套字典,它帮助我开始,但我仍然未能完成预期的结果

indented_text = """
# Level 1
## Level 2
### Level 3
#### Level 4
##### Level 5
###### Level 6
##### Level 5
#### Level 4
##### Level 5
###### Level 6
### Level 3
#### Level 4
## Level 2
### Level 3
#### Level 4
#### Level 4
### Level 3
"""
class Node:
def __init__(self, indented_line):
# self.t = t
# self.d = d
# self.p = {}
# self.v = v ---------
# self.c = [] ------
self.t = 'list_item'
self.d = indented_line.index('# ') # len(indented_line) - len(indented_line.lstrip())
self.p = {}
self.v = indented_line[self.d + 1:].strip()
self.c = []
def add_children(self, nodes):
childlevel = nodes[0].d
while nodes:
node = nodes.pop(0)
if node.d == childlevel: # add node as a child
self.c.append(node)
elif node.d > childlevel: # add nodes as grandchildren of the last child
nodes.insert(0,node)
self.c[-1].add_children(nodes)
elif node.d <= self.d: # this node is a sibling, no more children
nodes.insert(0,node)
return
root = Node('# root')
root.add_children([Node(line) for line in indented_text.splitlines() if line.strip()])

现在我需要输出为

{
"t": "heading",
"d": 1,
"p": {},
"v": "Level 1",
"c": [
{
"t": "heading",
"d": 2,
"p": {},
"v": "Level 2",
"c": [
{
"t": "heading",
"d": 3,
"p": {},
"v": "Level 3",
"c": [
{
"t": "heading",
"d": 4,
"p": {},
"v": "Level 4",
"c": [
{
"t": "heading",
"d": 5,
"p": {},
"v": "Level 5",
"c": [
{
"t": "heading",
"d": 6,
"p": {},
"v": "Level 6"
}
]
},
{
"t": "heading",
"d": 5,
"p": {},
"v": "Level 5"
}
]
},
{
"t": "heading",
"d": 4,
"p": {},
"v": "Level 4",
"c": [
{
"t": "heading",
"d": 5,
"p": {},
"v": "Level 5",
"c": [
{
"t": "heading",
"d": 6,
"p": {},
"v": "Level 6"
}
]
}
]
}
]
},
{
"t": "heading",
"d": 3,
"p": {},
"v": "Level 3",
"c": [
{
"t": "heading",
"d": 4,
"p": {},
"v": "Level 4"
}
]
}
]
},
{
"t": "heading",
"d": 2,
"p": {},
"v": "Level 2",
"c": [
{
"t": "heading",
"d": 3,
"p": {},
"v": "Level 3",
"c": [
{
"t": "heading",
"d": 4,
"p": {},
"v": "Level 4"
},
{
"t": "heading",
"d": 4,
"p": {},
"v": "Level 4"
}
]
},
{
"t": "heading",
"d": 3,
"p": {},
"v": "Level 3"
}
]
}
]
}

我无法完成并获得所需的输出…

我可以使用

来解决我的问题
json.dumps(root, default=lambda v: v.__dict__)

谢谢大家的插话,https://stackoverflow.com/users/843953/pranav-hosangadi为我指出了正确的方向

相关内容

  • 没有找到相关文章

最新更新