为了账号安全,请及时绑定邮箱和手机立即绑定

PythonJSON序列化一个Decimal对象

PythonJSON序列化一个Decimal对象

qq_笑_17 2019-07-06 16:06:24
PythonJSON序列化一个Decimal对象我有一个Decimal('3.9')作为对象的一部分,并希望将其编码为JSON字符串,该字符串应该如下所示{'x': 3.9}..我不关心客户端的精确性,所以浮点数是可以的。有什么好的方法来序列化这个吗?JSONDecoder不接受Decimal对象,并提前转换为浮点数{'x': 3.8999999999999999}这是错误的,而且将是对带宽的极大浪费。
查看完整描述

3 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

子类如何?json.JSONEncoder?

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)

然后像这样使用它:

json.dumps({'x': decimal.Decimal('5.5')}, cls=DecimalEncoder)


查看完整回答
反对 回复 2019-07-06
?
德玛西亚99

TA贡献1770条经验 获得超3个赞

Simplejson 2.1而更高的公司则支持十进制类型:

>>> json.dumps(Decimal('3.9'), use_decimal=True)'3.9'

请注意use_decimalTrue默认情况下:

def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
    allow_nan=True, cls=None, indent=None, separators=None,
    encoding='utf-8', default=None, use_decimal=True,
    namedtuple_as_object=True, tuple_as_array=True,
    bigint_as_string=False, sort_keys=False, item_sort_key=None,
    for_json=False, ignore_nan=False, **kw):

因此:

>>> json.dumps(Decimal('3.9'))'3.9'

希望这个特性将包含在标准库中。


查看完整回答
反对 回复 2019-07-06
?
饮歌长啸

TA贡献1951条经验 获得超3个赞

我想让大家知道,我在运行Python2.6.5的Web服务器上尝试了MichaPythMarczyk的答案,它运行得很好。但是,我升级到Python2.7,它停止工作了。我试着想出一种编码十进制对象的方法,这就是我想出来的:

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        return super(DecimalEncoder, self).default(o)

希望这能帮助那些在Python2.7中遇到问题的人。我测试过了,看起来很好。如果有人注意到我的解决方案中有任何错误,或者想出了更好的方法,请告诉我。


查看完整回答
反对 回复 2019-07-06
  • 3 回答
  • 0 关注
  • 1445 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信