Python: Serialization of json namedtuple classes

Asked

Viewed 66 times

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 ?

  • Traceback (most recent call last):&#xA; File "/home/brito/projetos/00-incolumepy/incolumepy/testes/handler_files/json/namedtuple2json00.py", line 5, in <module>&#xA; Emp.tojson = json.dumps(Emp._asdict())&#xA;TypeError: _asdict() missing 1 required positional argument: 'self'

  • 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, I want to add the tojson method to the namedtuple object.

  • And why do you need a method for this? It would not be enough to do json.dumps(a)?

  • @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.

  • But that way you would have the object, not just a dictionary.

Show 2 more comments

1 answer

1


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

Emp.tojson = lambda self: json.dumps(self._asdict())
  • Because it is inadvisable?

  • Look at the trouble you would have: https://stackoverflow.com/questions/6738987/extension-method-for-python-built-in-types and you cannot change standard types.

  • 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.

  • I recommend looking at this link: https://stackoverflow.com/questions/44320382/subclassing-python-namedtuple

Browser other questions tagged

You are not signed in. Login or sign up in order to post.