使用常规编码器使对象JSON可序列化

leo*_*sas 59 python serialization json monkeypatching

JSON序列化自定义非可序列化对象的常规方法是子类化json.JSONEncoder,然后将自定义编码器传递给转储.

它通常看起来像这样:

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, foo):
            return obj.to_json()

        return json.JSONEncoder.default(self, obj)

print json.dumps(obj, cls = CustomEncoder)
Run Code Online (Sandbox Code Playgroud)

我正在尝试做的是使用默认编码器进行序列化.我环顾四周但找不到任何东西.我的想法是编码器会看到一些字段来确定json编码.类似的东西__str__.也许是一个__json__领域.在python中有这样的东西吗?

我想制作一个模块的类,我正在使用JSON序列化给使用该软件包的每个人,而不必担心实现他们自己的[普通]自定义编码器.

mar*_*eau 72

正如我在对您的问题的评论中所说,在查看json模块的源代码之后,它似乎并不适合做您想要的事情.然而,目标可以通过所谓的猴子修补来实现 (请参阅问题什么是猴子补丁?).这可以在您的包的__init__.py初始化脚本中完成,并且会影响所有后续json模块序列化,因为模块通常只加载一次并且结果被缓存sys.modules.

补丁更改默认的json编码器default方法 - 默认值default().

为简单起见,这是一个作为独立模块实现的示例:

模块: make_json_serializable.py

""" Module that monkey-patches json module when it's imported so
JSONEncoder.default() automatically checks for a special "to_json()"
method and uses it to encode the object if found.
"""
from json import JSONEncoder

def _default(self, obj):
    return getattr(obj.__class__, "to_json", _default.default)(obj)

_default.default = JSONEncoder.default  # Save unmodified default.
JSONEncoder.default = _default # Replace it.
Run Code Online (Sandbox Code Playgroud)

使用它是微不足道的,因为通过简单地导入模块来应用补丁.

示例客户端脚本:

import json
import make_json_serializable  # apply monkey-patch

class Foo(object):
    def __init__(self, name):
        self.name = name
    def to_json(self):  # New special method.
        """ Convert to JSON format string representation. """
        return '{"name": "%s"}' % self.name

foo = Foo('sazpaz')
print(json.dumps(foo))  # -> "{\"name\": \"sazpaz\"}"
Run Code Online (Sandbox Code Playgroud)

要保留对象类型信息,特殊方法还可以将其包含在返回的字符串中:

        return ('{"type": "%s", "name": "%s"}' %
                 (self.__class__.__name__, self.name))
Run Code Online (Sandbox Code Playgroud)

这产生了以下包含类名的JSON:

"{\"type\": \"Foo\", \"name\": \"sazpaz\"}"
Run Code Online (Sandbox Code Playgroud)

Magick在这里说谎

比替换default()外观特别命名的方法更好的是,它能够自动序列化大多数Python对象,包括用户定义的类实例,而无需添加特殊方法.在研究了许多替代方案之后,使用该pickle模块的以下内容对我来说似乎最接近理想:

模块: make_json_serializable2.py

""" Module that imports the json module and monkey-patches it so
JSONEncoder.default() automatically pickles any Python objects
encountered that aren't standard JSON data types.
"""
from json import JSONEncoder
import pickle

def _default(self, obj):
    return {'_python_object': pickle.dumps(obj)}

JSONEncoder.default = _default  # Replace with the above.
Run Code Online (Sandbox Code Playgroud)

当然,例如,所有东西都不能被腌制 - 扩展类型.然而,有一些方法可以通过编写特殊方法来定义处理它们 - 类似于你建议和我之前描述的方法 - 但这样做对于少得多的情况可能是必要的.

无论如何,使用pickle协议还意味着通过在传入的字典中查找键的object_hook任何json.loads()调用提供自定义函数参数来重建原始Python对象相当容易'_python_object'.例如:

def as_python_object(dct):
    try:
        return pickle.loads(str(dct['_python_object']))
    except KeyError:
        return dct

pyobj = json.loads(json_str, object_hook=as_python_object)
Run Code Online (Sandbox Code Playgroud)

如果必须在很多地方完成,那么定义一个自动提供额外关键字参数的包装函数可能是值得的:

json_pkloads = functools.partial(json.loads, object_hook=as_python_object)

pyobj = json_pkloads(json_str)
Run Code Online (Sandbox Code Playgroud)

当然,这也可以将其修补到json模块中,使函数成为默认值object_hook(而不是None).

我的想法用pickle答案雷蒙德赫廷杰另一个JSON序列化的问题,就是我认为非常可靠以及官方源(如在Python核心开发人员).

Python 3的可移植性

上面的代码不能像Python 3中所示那样工作,因为json.dumps()返回一个无法处理的bytes对象JSONEncoder.但是这种方法仍然有效.一个简单的方法来解决该问题是latin1"解码",从返回的值pickle.dumps(),然后选择"编码",它从latin1它传递到之前pickle.loads()as_python_object()功能.这工作,因为任意的二进制字符串是有效的latin1,可总是被解码为Unicode,然后编码返回到原始字符串再次(在指出这个答案斯文Marnach).

(虽然以下在Python 2中运行良好,但latin1它的解码和编码是多余的.)

from decimal import Decimal

class PythonObjectEncoder(json.JSONEncoder):
    def default(self, obj):
        return {'_python_object': pickle.dumps(obj).decode('latin1')}

def as_python_object(dct):
    try:
        return pickle.loads(dct['_python_object'].encode('latin1'))
    except KeyError:
        return dct

data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'},
        Decimal('3.14')]
j = json.dumps(data, cls=PythonObjectEncoder, indent=4)
data2 = json.loads(j, object_hook=as_python_object)
assert data == data2  # both should be same
Run Code Online (Sandbox Code Playgroud)


Ara*_* Ve 12

您可以像这样扩展dict类:

#!/usr/local/bin/python3
import json

class Serializable(dict):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # hack to fix _json.so make_encoder serialize properly
        self.__setitem__('dummy', 1)

    def _myattrs(self):
        return [
            (x, self._repr(getattr(self, x))) 
            for x in self.__dir__() 
            if x not in Serializable().__dir__()
        ]

    def _repr(self, value):
        if isinstance(value, (str, int, float, list, tuple, dict)):
            return value
        else:
            return repr(value)

    def __repr__(self):
        return '<%s.%s object at %s>' % (
            self.__class__.__module__,
            self.__class__.__name__,
            hex(id(self))
        )

    def keys(self):
        return iter([x[0] for x in self._myattrs()])

    def values(self):
        return iter([x[1] for x in self._myattrs()])

    def items(self):
        return iter(self._myattrs())
Run Code Online (Sandbox Code Playgroud)

现在,要使用常规编码器使您的类可序列化,请扩展'Serializable':

class MySerializableClass(Serializable):

    attr_1 = 'first attribute'
    attr_2 = 23

    def my_function(self):
        print('do something here')


obj = MySerializableClass()
Run Code Online (Sandbox Code Playgroud)

print(obj) 将打印如下:

<__main__.MySerializableClass object at 0x1073525e8>
Run Code Online (Sandbox Code Playgroud)

print(json.dumps(obj, indent=4)) 将打印如下:

{
    "attr_1": "first attribute",
    "attr_2": 23,
    "my_function": "<bound method MySerializableClass.my_function of <__main__.MySerializableClass object at 0x1073525e8>>"
}
Run Code Online (Sandbox Code Playgroud)


Yoa*_*ger 5

我建议将 hack 放入类定义中。这样,一旦定义了类,它就支持 JSON。例子:

import json

class MyClass( object ):

    def _jsonSupport( *args ):
        def default( self, xObject ):
            return { 'type': 'MyClass', 'name': xObject.name() }

        def objectHook( obj ):
            if 'type' not in obj:
                return obj
            if obj[ 'type' ] != 'MyClass':
                return obj
            return MyClass( obj[ 'name' ] )
        json.JSONEncoder.default = default
        json._default_decoder = json.JSONDecoder( object_hook = objectHook )

    _jsonSupport()

    def __init__( self, name ):
        self._name = name

    def name( self ):
        return self._name

    def __repr__( self ):
        return '<MyClass(name=%s)>' % self._name

myObject = MyClass( 'Magneto' )
jsonString = json.dumps( [ myObject, 'some', { 'other': 'objects' } ] )
print "json representation:", jsonString

decoded = json.loads( jsonString )
print "after decoding, our object is the first in the list", decoded[ 0 ]
Run Code Online (Sandbox Code Playgroud)

  • 这种方法的一个显着限制是,正如目前所写的,它不能很好地与其他方法一起使用,因为一次不能有多个类使用这种方法,否则它们会互相踩踏JSON 支持代码。即使它在这种情况下确实有效,也需要复制类似的支持代码并将其放置在每个类中。然而,解决这两个问题是可能的。 (4认同)