我有以下对象:
class Heading:
def __init__(self, text):
self._text = text
self._subheadings = []
def add_subheading(self, sub):
self._subheadings.append(sub)
myh1类型Headingeg 包含以下结构:
所以这个h1包含(你不能看到全部)4个h2s。h2 可能包含也可能不包含 h3s 等等。递归地,每个对象都是类型Heading并且是_subheadings.
我现在想将此结构序列化为 json 字符串。实现这一目标最顺利的方法是什么?否则我会构建这样的东西(显然它还没有完成,现在它只是遍历所有标题):
def jsonize_headings(self):
# main object
headings = {}
# h1 heading
headings["h1_heading"] = self.h1_heading.text
# h2 headings
for h2 in self.h1_heading.subheadings:
h2_dict = dict()
h2_dict["h2_heading"] = h2.text
# h3 headings
for h3 in h2.subheadings:
h3_dict = dict()
h3_dict["h3_heading"] = h3.text
# h4 headings
for h4 in h3.subheadings:
h4_dict = dict()
h4_dict["h4_heading"] = h4.text
# h5 headings
for h5 in h4.subheadings:
h5_dict = dict()
h5_dict["h5_heading"] = h5.text
# h6 headings
for h6 in h5.subheadings:
h6_dict = dict()
h6_dict["h6_heading"] = h6.text
最后结果:
class Heading:
def __init__(self, text):
self._text = text
self._subheadings = []
def add_subheading(self, sub):
self._subheadings.append(sub)
@property
def text(self):
return self._text
@property
def subheadings(self):
return self._subheadings
@classmethod
def to_dict(cls, _obj):
def _to_dict(d, c=1):
e = dict()
e[f"h{c}_heading"] = d.text
if d.subheadings:
e[f"h{c+1}_headings"] = [_to_dict(sub, c+1) for sub in d.subheadings]
return e
return _to_dict((_obj))
呼啦一阵风
相关分类