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 guys, I developed the above solution to turn a class into json.
I know that the __Dict__ does not exist in the namedtuple, and it is possible to evoke the method _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 take the tojson equivalent function? I tried it from the below mode and it doesn’t work... :/
Emp.tojson = json.dumps(Emp._asdict()) #error
Excerpt running on ideone: https://ideone.com/6VaFDN
What’s the mistake ?
– Onilol
Traceback (most recent call last):
 File "/home/brito/projetos/00-incolumepy/incolumepy/testes/handler_files/json/namedtuple2json00.py", line 5, in <module>
 Emp.tojson = json.dumps(Emp._asdict())
TypeError: _asdict() missing 1 required positional argument: 'self'
– britodfbr
What you can do is subclass the namedtuple and create the function there but I wouldn’t recommend it, the work would be great. What do you really want to do? See the link in English: https://stackoverflow.com/questions/44320382/subclassing-python-namedtuple
– Onilol
@Onilol, I want to add the tojson method to the namedtuple object.
– britodfbr
And why do you need a method for this? It would not be enough to do
json.dumps(a)
?– Woss
@Andersoncarloswoss, In precise object practice to simplify some tasks, but without implementing a class for this. Where the use of dictionaries instead of objects would be too complex.
– britodfbr
But that way you would have the object, not just a dictionary.
– Woss