将复杂的python对象序列化/反序列化为JSON的最佳实践是什么,它可以解释子类化并防止同一对象的多个副本(假设我们知道如何区分同一类的不同实例)多次存储?在
简而言之,我正在写一个小的科学图书馆,希望人们能使用它。但是在看了raymondhettinger的谈话之后,我决定对我来说实现子类化感知行为是一个很好的练习。到目前为止一切顺利,但现在我开始执行JSON序列化任务。在
到目前为止,我环顾四周,发现了以下关于Python中JSON序列化的信息:
我遇到的两个主要障碍是解释可能的子类化,每个实例一个副本。在
在多次尝试用纯python解决它之后,在没有对object的JSON表示进行任何更改的情况下,我终于明白了,在反序列化JSON时,现在有办法知道之前序列化了哪个类heir的实例。所以我们应该提一下,我最后得出这样的结论:
class MyClassJSONEncoder(json.JSONEncoder):
@classmethod
def represent_object(cls, obj):
"""
This is a way to serialize all built-ins as is, and all complex objects as their id, which is hash(obj) in this implementation
"""
if isinstance(obj, (int, float, str, Boolean)) or value is None:
return obj
elif isinstance(obj, (list, dict, tuple)):
return cls.represent_iterable(obj)
else:
return hash(obj)
@classmethod
def represent_iterable(cls, iterable):
"""
JSON supports iterables, so they shall be processed
"""
if isinstance(iterable, (list, tuple)):
return [cls.represent_object(value) for value in iterable]
elif isinstance(iterable, dict):
return [cls.represent_object(key): cls.represent_object(value) for key, value in iterable.items()]
def default(self, obj):
if isinstance(obj, MyClass):
result = {"MyClass_id": hash(obj),
"py__class__": ":".join([obj.__class__.__module, obj.__class__.__qualname__]}
for attr, value in self.__dict__.items():
result[attr] = self.represent_object(value)
return result
return super().default(obj) # accounting for JSONEncoder subclassing
在这里,子类化的说明在
^{pr2}$jsondecorder的实现如下:
class MyClassJSONDecoder(json.JSONDecoder):
def decode(self, data):
if isinstance(data, str):
data = super().decode(data)
if "py__class__" in data:
module_name, class_name = data["py__class__"].split(":")
object_class = getattr(importlib.__import__(module_name, fromlist=[class_name]), class_name)
else:
object_class = MyClass
data = {key, value for key, value in data.items() if not key.endswith("_id") or key != "py__class__"}
return object_class(**data)
如可以看到的,在这里我们考虑了在对象的JSON表示中具有“Pyth-Curasexy”属性的子类,如果没有这样的属性(如果是C++,则是由另一个程序生成的JSON,并且它们只想传递我们关于PrimeMyC类对象的信息,创建MyClass
实例的默认方法
被追查。顺便说一句,这就是为什么不能为所有对象创建一个jsondeconder的原因:如果没有指定py__class__
,那么它必须有一个默认的类值来创建。在
就每个实例的一个副本而言,这是通过这样一个事实来实现的:该对象用一个特殊的JSON键myclass_id
序列化,所有属性值都序列化为原语(lists
,tuples
,dicts
,并且保留了内置的,而当复杂对象是某个属性的值时,只存储其哈希值)。这种存储对象哈希的方法允许将每个对象精确地序列化一次,然后,在知道要从json表示中解码的对象的结构之后,它可以查找相应的对象并最终分配它们。为了简单地说明这一点,可以观察到以下示例:
class MyClass(object):
json_encoder = MyClassJSONEncoder()
json_decoder = MyClassJSONDecoder()
def __init__(self, attr1):
self.attr1 = attr1
self.attr2 = [complex_object_1, complex_object_2]
def to_json(self, top_level=None):
if top_level is None:
top_level = {}
top_level["my_class"] = self.json_encoder.encode(self)
top_level["complex_objects"] = [obj.to_json(top_level=top_level) for obj in self.attr2]
return top_level
@classmethod
def from_json(cls, data, class_specific_data=None):
if isinstance(data, str):
data = json.loads(data)
if class_specific_data is None:
class_specific_data = data["my_class"] # I know the flat structure of json, and I know the attribute name, this class will be stored
result = cls.json_decoder.decode(class_spcific_data)
# repopulate complex valued attributes with real python objects
# rather than their id aliases
complex_objects = {co_data["ComplexObject_id"]: ComplexObject.from_json(data, class_specific_data=co_data) for co_data in data["complex_objects"]]
result.complex_objects = [c_o for c_o_id, c_o in complex_objects.items() if c_o_id in self.complex_objects]
# finish such repopulation
return result
这是一条正确的路吗?有没有更有力的方法?在这种非常特殊的情况下,我是否错过了一些要实现的编程模式?在
我只想了解实现JSON序列化的最正确的python方法是什么,它可以解释子类化并防止存储同一对象的多个副本。在
目前没有回答
相关问题 更多 >
编程相关推荐