我有一个包含一些小数的 python 对象。这导致 json.dumps() 中断。
我从 SO 得到了以下解决方案(例如Python JSON 序列化一个 Decimal 对象),但推荐的解决方案仍然不起作用。Python 网站 - 有完全相同的答案。
任何建议如何使这项工作?
谢谢。下面是我的代码。看起来 dumps() 甚至没有进入专门的编码器。
clayton@mserver:~/python> cat test1.py
import json, decimal
class DecimalEncoder(json.JSONEncoder):
def _iterencode(self, o, markers=None):
print "here we go o is a == ", type(o)
if isinstance(o, decimal.Decimal):
print "woohoo! got a decimal"
return (str(o) for o in [o])
return super(DecimalEncoder, self)._iterencode(o, markers)
z = json.dumps( {'x': decimal.Decimal('5.5')}, cls=DecimalEncoder )
print z
clayton@mserver:~/python> python test1.py
Traceback (most recent call last):
File "test1.py", line 11, in <module>
z = json.dumps( {'x': decimal.Decimal('5.5')}, cls=DecimalEncoder )
File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/encoder.py", line 201, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/encoder.py", line 264, in iterencode
return _iterencode(o, 0)
File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/encoder.py", line 178, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: Decimal('5.5') is not JSON serializable
clayton@mserver:~/python>