您好我正在使用JSON编码器,其中pickle.dumps()给了我奇怪的输出。输出结果如下:
"cdecimal Decimal p0 (S'2097369' p1 tp2 Rp3 .",
虽然,它应该是:2097369
代码段是:
class PythonObjectEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, (list, dict, unicode, int, float, str, bool, type(None))):
return JSONEncoder.default(self, obj)
return pickle.dumps(obj)
def as_python_object(dct):
if '_python_object' in dct:
return pickle.loads('')
return dct
任何人都可以告诉我出了什么问题,我怎样才能找回所需的值?
答案 0 :(得分:0)
我认为这就是你要找的东西。 JSON不支持的类型使用pickle
序列化为字符串,并以格式存储以指示它是Python对象。 object_hook
用于识别该格式,并在json.loads
期间将pickled对象转换回Python对象:
from decimal import Decimal
import json
import pickle
class PythonObjectEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (dict,list,tuple,str,unicode,int,long,float,bool,type(None))):
return json.JSONEncoder.default(self,obj)
return {'_python_object_':pickle.dumps(obj)}
def as_python_object(dct):
if u'_python_object_' in dct:
return pickle.loads(dct[u'_python_object_'])
return dct
obj = {'a':1,'b':'string','c':1.2,'d':Decimal('123.456')}
print obj # original object
j = json.dumps(obj,cls=PythonObjectEncoder,indent=2)
print j # encoded object
obj = json.loads(j,object_hook=as_python_object)
print obj # decoded object
输出:
{'a': 1, 'c': 1.2, 'b': 'string', 'd': Decimal('123.456')}
{
"a": 1,
"c": 1.2,
"b": "string",
"d": {
"_python_object_": "cdecimal\nDecimal\np0\n(S'123.456'\np1\ntp2\nRp3\n."
}
}
{u'a': 1, u'c': 1.2, u'b': u'string', u'd': Decimal('123.456')}