Serializing a Python namedtuple to json

后端 未结 11 1748
梦谈多话
梦谈多话 2020-11-29 18:50

What is the recommended way of serializing a namedtuple to json with the field names retained?

Serializing a namedtuple to json results in only the valu

11条回答
  •  没有蜡笔的小新
    2020-11-29 19:29

    It recursively converts the namedTuple data to json.

    print(m1)
    ## Message(id=2, agent=Agent(id=1, first_name='asd', last_name='asd', mail='2@mai.com'), customer=Customer(id=1, first_name='asd', last_name='asd', mail='2@mai.com', phone_number=123123), type='image', content='text', media_url='h.com', la=123123, ls=4512313)
    
    def reqursive_to_json(obj):
        _json = {}
    
        if isinstance(obj, tuple):
            datas = obj._asdict()
            for data in datas:
                if isinstance(datas[data], tuple):
                    _json[data] = (reqursive_to_json(datas[data]))
                else:
                     print(datas[data])
                    _json[data] = (datas[data])
        return _json
    
    data = reqursive_to_json(m1)
    print(data)
    {'agent': {'first_name': 'asd',
    'last_name': 'asd',
    'mail': '2@mai.com',
    'id': 1},
    'content': 'text',
    'customer': {'first_name': 'asd',
    'last_name': 'asd',
    'mail': '2@mai.com',
    'phone_number': 123123,
    'id': 1},
    'id': 2,
    'la': 123123,
    'ls': 4512313,
    'media_url': 'h.com',
    'type': 'image'}
    

提交回复
热议问题