1 回答

TA贡献1802条经验 获得超6个赞
您可以使用递归itertools.count:
import itertools
class Heading:
def __init__(self, text):
self._text = text
self._subheadings = []
def add_subheading(self, sub):
self._subheadings.append(sub)
@classmethod
def to_dict(cls, _obj):
c = itertools.count(1)
def _to_dict(d):
return {f'h{next(c)}_heading':d._text, 'children':list(map(_to_dict, d._subheadings))}
return _to_dict(_obj)
现在:
import json
h, c1, c2 = Heading('test_header1'), Heading('test_sub_header1'), Heading('test_sub_header2')
c1.add_subheading(c2)
h.add_subheading(c1)
print(json.dumps(Heading.to_dict(h), indent=4))
输出:
{
"h1_heading": "test_header1",
"children": [
{
"h2_heading": "test_sub_header1",
"children": [
{
"h3_heading": "test_sub_header2",
"children": []
}
]
}
]
}
这是一个简化的示例,但是,可以轻松更新递归过程以支持自定义键名等。
添加回答
举报