I am looking for a way to encode custom objects to dict in Python using a class decorator to provide the name of the variables that should be included in the resulting dict as arguments. With the dict, I would be able to use json.dumps(custom_object_dict)
to make the transformation to JSON.
In other words, the idea is to have the following @encoder
class decorator:
@encoder(variables=['firstname', 'lastname'], objects=['professor'], lists=['students'])
class Course(Object):
def __init__(self, firstname, lastname, professor, students):
self.firstname = firstname
self.lastname = lastname
self.professor = professor
self.students = students
#instance of Course:
course = Course("john", "smith", Professor(), [Student(1), Student(2, "john")])
This decorator would allow me to do something similar to the following:
Option A:
json = json.dumps(course.to_dict())
Option B:
json = json.dumps(course.dict_representation)
...Or something of the like
So the question is: How to write this encoder, where the only real requirements are:
- Encoder should only encode variables that are provided through the decorator
- Encoder should be able to encode other objects (e.g.: professor inside Courses, if the Professor class also has the decorator
@encoder
- Should also be able to encode a list of other objects (e.g.: students inside course, counting that the class Students would also have to
@encoder
decorator)
I have researched different ways of doing that (including creating a class that inherits from json.JSONEncoder), but none seemed to do exactly what I had in mind. Would anyone be able to help me?
Thanks in advance!