0

嗨,我正在使用 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

谁能告诉我出了什么问题,我怎样才能找回想要的价值?

4

1 回答 1

0

我想这就是你要找的。JSON 不支持的类型被序列化为字符串,pickle并以一种格式存储,以表明它是一个 Python 对象。Anobject_hook用于识别该格式并将腌制对象转换回 Python 对象json.loads

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')}
于 2013-09-07T17:39:36.290 回答