1 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用遞歸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)
現(xiàn)在:
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": []
}
]
}
]
}
這是一個(gè)簡(jiǎn)化的示例,但是,可以輕松更新遞歸過(guò)程以支持自定義鍵名等。
添加回答
舉報(bào)