Python: Serialization of namedtuple classes in json

0
import json
from collection import namedtuple


class Employee:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def tojson(self):
        return json.dumps(self.__dict__)

Hello everyone, I've developed the above solution to turn a class into json.

I know that __ dict __ does not exist in namedtuple, and that you can evoke _asdict () to replace it.

Emp = namedtuple('Emp', 'name age')
a = Emp('Luc', 10)
json.dumps(a._asdict())

How can I create a method in the namedtuple class to assume the tojson equivalent function? I tried the way below and it does not work ...: /

Emp.tojson = json.dumps(Emp._asdict()) #error

Excerpt running on ideone: link

    
asked by anonymous 08.04.2018 / 22:55

1 answer

0

Although you do not advise against this practice, what you want to do can be done as follows:

Emp.tojson = lambda self: json.dumps(self._asdict())
    
09.04.2018 / 16:48