Serializing a Python namedtuple to json

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

    It's impossible to serialize namedtuples correctly with the native python json library. It will always see tuples as lists, and it is impossible to override the default serializer to change this behaviour. It's worse if objects are nested.

    Better to use a more robust library like orjson:

    import orjson
    from typing import NamedTuple
    
    class Rectangle(NamedTuple):
        width: int
        height: int
    
    def default(obj):
        if hasattr(obj, '_asdict'):
            return obj._asdict()
    
    rectangle = Rectangle(width=10, height=20)
    print(orjson.dumps(rectangle, default=default))
    

    =>

    {
        "width":10,
        "height":20
    }
    

提交回复
热议问题