Serializing a Python namedtuple to json

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

    It looks like you used to be able to subclass simplejson.JSONEncoder to make this work, but with the latest simplejson code, that is no longer the case: you have to actually modify the project code. I see no reason why simplejson should not support namedtuples, so I forked the project, added namedtuple support, and I'm currently waiting for my branch to be pulled back into the main project. If you need the fixes now, just pull from my fork.

    EDIT: Looks like the latest versions of simplejson now natively support this with the namedtuple_as_object option, which defaults to True.

提交回复
热议问题