在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
)。