Question

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:

  1. Encoder should only encode variables that are provided through the decorator
  2. Encoder should be able to encode other objects (e.g.: professor inside Courses, if the Professor class also has the decorator @encoder
  3. 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!

Était-ce utile?

La solution

Maybe something like this (just a fast sketch):

#! /usr/bin/python3.2

import json

class Jsonable:
    def __init__ (self, *args):
        self.fields = args

    def __call__ (self, cls):
        cls._jsonFields = self.fields
        def toDict (self):
            d = {}
            for f in self.__class__._jsonFields:
                v = self.__getattribute__ (f)
                if isinstance (v, list):
                    d [f] = [e.jsonDict if hasattr (e.__class__, '_jsonFields') else e for e in v]
                    continue
                d [f] = v.jsonDict if hasattr (v.__class__, '_jsonFields') else v
            return d
        cls.toDict = toDict

        oGetter = cls.__getattribute__
        def getter (self, key):
            if key == 'jsonDict': return self.toDict ()
            return oGetter (self, key)
        cls.__getattribute__ = getter

        return cls

@Jsonable ('professor', 'students', 'primitiveList')
class Course:
    def __init__ (self, professor, students):
        self.professor = professor
        self.students = students
        self.toBeIgnored = 5
        self.primitiveList = [0, 1, 1, 2, 3, 5]

@Jsonable ('firstname', 'lastname')
class Student:
    def __init__ (self, firstname, lastname, score = 42):
        self.firstname = firstname
        self.lastname = lastname
        self.score = score

@Jsonable ('title', 'name')
class Professor:
    def __init__ (self, name, title):
        self.title = title
        self.name = name

p = Professor ('Ordóñez', 'Dra')
s1 = Student ('Juan', 'Pérez')
s2 = Student ('Juana', 'López')
s3 = Student ('Luis', 'Jerez')
s4 = Student ('Luisa', 'Gómez')
c = Course (p, [s1, s2, s3, s4] )

print (json.dumps (c.jsonDict) )

You might want to check for other iterables besides list or something like if hasattr (v, __iter__) and not isinstance (v, str).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top