Serializing a Python namedtuple to json

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}'

Leave a Comment