如何递归地对python对象进行jsonize

我有以下对象:


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))


蝴蝶刀刀
浏览 120回答 1
1回答

呼啦一阵风

您可以使用递归itertools.count:import itertoolsclass 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 jsonh, 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": []            }        ]      }   ]  }这是一个简化的示例,但是,可以轻松更新递归过程以支持自定义键名等。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python