为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

蝴蝶刀刀 2022-06-22 18:40:06
我有以下对象: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))
查看完整描述

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": []

            }

        ]

      }

   ]  

}

这是一个简化的示例,但是,可以轻松更新递归过程以支持自定义键名等。


查看完整回答
反对 回复 2022-06-22
  • 1 回答
  • 0 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号