如何使simplejson可序列化类

编程入门 行业动态 更新时间:2024-10-10 05:19:15
本文介绍了如何使simplejson可序列化类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个这样定义的类

class A: def __init__(self): self.item1 = None def __repr__(self): return str(self.__dict__)

当我这样做:

>>> import simplejson >>> myA = A() >>> simplejson.dumps(myA) TypeError: {'item1': None} is not JSON serializable

我找不到原因.

我是否需要向A添加任何特定方法以使simplejson序列化我的类对象?

Do I need to add any particular method to A for simplejson to serialize my class object?

推荐答案

您不能使用simplejson序列化任意对象.您需要将default和object_hook传递给dump和load.这是一个示例:

You can't serialize arbitrary objects with simplejson. You need to pass a default and object_hook to dump and load. Here's an example:

class SerializerRegistry(object): def __init__(self): self._classes = {} def add(self, cls): self._classes[cls.__module__, cls.__name__] = cls return cls def object_hook(self, dct): module, cls_name = dct.pop('__type__', (None, None)) if cls_name is not None: return self._classes[module, cls_name].from_dict(dct) else: return dct def default(self, obj): dct = obj.to_dict() dct['__type__'] = [type(obj).__module__, type(obj).__name__] return dct registry = SerializerRegistry() @registry.add class A(object): def __init__(self, item1): self.item1 = item1 def __repr__(self): return str(self.__dict__) def to_dict(self): return dict(item1=self.item1) @classmethod def from_dict(cls, dct): return cls(**dct) s = json.dumps(A(1), default=registry.default) a = json.loads(s, object_hook=registry.object_hook)

结果如下:

>>> s '{"item1": 1, "__type__": ["__main__", "A"]}' >>> a {'item1': 1}

但是您真正需要的是一个函数default,该函数从您要序列化的对象中创建字典,以及一个函数object_hook,当给定字典时,该函数返回一个对象(正确类型),如果字典还不够.最好的方法是在可序列化类上具有从对象创建字典并将其构造回去的方法,并具有可识别字典所属类的映射.

But what you really need is a function default that creates dictionary from the objects that you wish to serialize, and a function object_hook that returns an object (of the correct type) when it is given a dictionary if a dictionary isn't enough. The best approach is to have methods on the serializable classes that create a dict from the object and that construct it back, and also to have a mapping that recognizes to which class the dictionaries belong.

还可以将标识符添加到类中,以用作_classes的索引.这样,如果您要上课,就不会有问题.

You can also add an identifier to the classes to be used as an index for _classes. This way you wouldn't have issues if you have to move a class.

更多推荐

如何使simplejson可序列化类

本文发布于:2023-11-11 08:48:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577935.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列化   simplejson

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!