我正在寻找一种方法来使用类装饰器将自定义对象编码为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)
……或类似的东西
所以问题是:如何编写这个编码器,唯一真正的要求是:
>编码器应该只编码通过装饰器提供的变量
>编码器应该能够编码其他对象(例如:课程内的教授,如果教授类也有装饰器@encoder
>还应该能够编码其他对象的列表(例如:课程内的学生,计算班级学生也需要@encoder装饰器)
我研究了不同的方法(包括创建一个继承自json.JSONEncoder的类),但似乎没有一个完全按照我的想法.有人能帮助我吗?
提前致谢!
解决方法:
也许这样的事情(只是一个快速草图):
#! /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) )
您可能希望检查除列表之外的其他迭代或类似ifattr(v,__ iter_)而不是isinstance(v,str).