4

我正在寻找一种使用类装饰器将自定义对象编码为 Python 中的 dict 的方法,以提供应作为参数包含在结果 dict 中的变量的名称。有了 dict,我就可以用来json.dumps(custom_object_dict)转换为 JSON。

换句话说,这个想法是有以下@encoder类装饰器:

@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")])

这个装饰器可以让我做类似于以下的事情:

选项 A:

json = json.dumps(course.to_dict())

选项 B:

json = json.dumps(course.dict_representation)

...或类似的东西

所以问题是:如何编写这个编码器,唯一真正的要求是:

  1. 编码器应该只编码通过装饰器提供的变量
  2. 编码器应该能够编码其他对象(例如:课程中的教授,如果教授类也有装饰器@encoder
  3. 还应该能够编码其他对象的列表(例如:课程内的学生,计算班级学生也必须@encoder装饰)

我研究了不同的方法(包括创建一个继承自 json.JSONEncoder 的类),但似乎没有一个完全符合我的想法。有人可以帮助我吗?

提前致谢!

4

1 回答 1

2

也许是这样的(只是一个快速草图):

#! /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) )

您可能想检查除listif之外的其他可迭代对象hasattr (v, __iter__) and not isinstance (v, str)

于 2013-02-16T03:18:35.480 回答