class DecimalEncoder(json.JSONEncoder):
def _iterencode(self, o, markers=None):
if isinstance(o, decimal.Decimal):
# wanted a simple yield str(o) in the next line,
# but that would mean a yield on the line with super(...),
# which wouldn't work (see my comment below), so...
return (str(o) for o in [o])
return super(DecimalEncoder, self)._iterencode(o, markers)
Simplejson 2.1及更高版本对十进制类型具有本机支持:
请注意,
use_decimal
默认为True
:所以:
希望这个特性将包含在标准库中。
我想让大家知道,我在运行Python 2.6.5的web服务器上尝试了MichałMarczyk的答案,它运行得很好。但是,我升级到了python2.7,它停止了工作。我试着想出一种编码十进制对象的方法,这就是我想到的:
希望这能帮助那些对Python2.7有问题的人。我测试过了,看起来效果不错。如果有人发现我的解决方案中有任何错误或想出更好的方法,请告诉我。
子类化
json.JSONEncoder
怎么样?然后像这样使用它:
相关问题 更多 >
编程相关推荐