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