如何使simplejson可序列化类 [英] How to make simplejson serializable class

查看:218
本文介绍了如何使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序列化任意对象.您需要将defaultobject_hook传递给dumpload.这是一个示例:

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可序列化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆