我正在寻找一种方法,使用类装饰器将自定义对象编码为Python,以提供应该作为参数包含在生成的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的类),但似乎没有一个完全按照我的想法行事。有人能帮助我吗?
提前致谢!
答案 0 :(得分: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) )
除了list
或hasattr (v, __iter__) and not isinstance (v, str)
之外,您可能还需要检查其他可迭代的内容。