Python:如何在simplejson.dumps()中自定义默认字节处理?

时间:2015-02-27 14:39:57

标签: python python-3.x simplejson

bytes的最新版本中使用simplejson.dumps()时,是否有一种干净的方式来自定义simplejson个对象的处理? (我使用的是3.5.3)

我尝试使用default属性,该属性在json.dumps()和旧版simplejson(< 3.0.0?)中正常工作。但是,最近版本的simplejson尝试使用指定的编码对bytes进行解码,因此bytes会跳过default处理程序。

我也尝试过设置encoding=None,但这会导致异常。

#!/usr/bin/python3.4
import json
import simplejson
from decimal import Decimal

def _encoder(data):
    if isinstance(data, bytes):
        return 'BYTES!'
    if isinstance(data, Decimal):
        return 'DECIMAL!'
    raise TypeError('No json encoder for {}'.format(type(data)))

data = {'d': Decimal(1), 'b': b'test'}

print(json.dumps(data, default=_encoder))
# works as expected: {"d": "DECIMAL!", "b": "BYTES!"}

print(simplejson.dumps(data, default=_encoder, use_decimal=False))
# does not work for bytes: {"d": "DECIMAL!", "b": "test"}

simplejson允许您扩展JSONEncoder,但似乎没有一个好地方可以挂钩单个嵌套对象的编码。例如,在我的调试中,JSONEncoder::iterencode将整个字典传递给外部函数(_iterencode)。

0 个答案:

没有答案