Serializing a Python namedtuple to json

后端 未结 11 1735
梦谈多话
梦谈多话 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:14

    There is a more convenient solution is to use the decorator (it uses the protected field _fields).

    Python 2.7+:

    import json
    from collections import namedtuple, OrderedDict
    
    def json_serializable(cls):
        def as_dict(self):
            yield OrderedDict(
                (name, value) for name, value in zip(
                    self._fields,
                    iter(super(cls, self).__iter__())))
        cls.__iter__ = as_dict
        return cls
    
    #Usage:
    
    C = json_serializable(namedtuple('C', 'a b c'))
    print json.dumps(C('abc', True, 3.14))
    
    # or
    
    @json_serializable
    class D(namedtuple('D', 'a b c')):
        pass
    
    print json.dumps(D('abc', True, 3.14))
    

    Python 3.6.6+:

    import json
    from typing import TupleName
    
    def json_serializable(cls):
        def as_dict(self):
            yield {name: value for name, value in zip(
                self._fields,
                iter(super(cls, self).__iter__()))}
        cls.__iter__ = as_dict
        return cls
    
    # Usage:
    
    @json_serializable
    class C(NamedTuple):
        a: str
        b: bool
        c: float
    
    print(json.dumps(C('abc', True, 3.14))
    

提交回复
热议问题