Serializing a Python namedtuple to json

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

    This is an old question. However:

    A suggestion for all those with the same question, think carefully about using any of the private or internal features of the NamedTuple because they have before and will change again over time.

    For example, if your NamedTuple is a flat value object and you're only interested in serializing it and not in cases where it is nested into another object, you could avoid the troubles that would come up with __dict__ being removed or _as_dict() changing and just do something like (and yes this is Python 3 because this answer is for the present):

    from typing import NamedTuple
    
    class ApiListRequest(NamedTuple):
      group: str="default"
      filter: str="*"
    
      def to_dict(self):
        return {
          'group': self.group,
          'filter': self.filter,
        }
    
      def to_json(self):
        return json.dumps(self.to_dict())
    

    I tried to use the default callable kwarg to dumps in order to do the to_dict() call if available, but that didn't get called as the NamedTuple is convertible to a list.

提交回复
热议问题