Serializing a Python namedtuple to json

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

    If it's just one namedtuple you're looking to serialize, using its _asdict() method will work (with Python >= 2.7)

    >>> from collections import namedtuple
    >>> import json
    >>> FB = namedtuple("FB", ("foo", "bar"))
    >>> fb = FB(123, 456)
    >>> json.dumps(fb._asdict())
    '{"foo": 123, "bar": 456}'
    

提交回复
热议问题