python3.5json序列化Decimal obj

2024-09-30 01:24:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将一个十进制值:999999.99990000005编码成json,同时不丢失精度,也不将表示形式更改为字符串。应为{ "prc" : 999999.99990000005 }

从[this post][1]我有这个代码。在

import json
import decimal

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

y = { 'prc' : decimal.Decimal('999999.99990000005')}

但它产生了一个字符串

^{pr2}$

isinstance中将str(o)替换为float(o)将截断该数字。 有没有办法得到非字符串结果? P、 我不能使用任何外部模块,比如simplejson。在

编辑: 如果我将值保存为字符串,下面也会生成一个字符串。在

>>> x = json.loads("""{ "cPrc" : "999999.99990000005" }""", parse_float=decimal.Decimal)
>>> x
{'cPrc': '999999.99990000005'}

Tags: 字符串importselfjsondefault编码returnfloat
2条回答

它不是最漂亮的,但如果你坚持使用json,我们可以创建一个自定义解码器,并让我们的编码器在处理十进制数据时指定类型。在

class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            return {
                "_type": "decimal",
                "value": str(obj)
            }
        return super(DecimalEncoder, self).default(obj)

上面的代码添加decimal类型作为解码器的标志,并将decimal编码为字符串以保持精度。在

^{pr2}$

解码器检查decimal类型标志,如果是,则使用decimal构造函数。对于所有其他实例,它使用默认解码

input = { 'prc' : decimal.Decimal('999999.99990000005')}
encoded = json.dumps(input, cls=DecimalEncoder)
decoded = json.loads(encoded, cls=DecimalDecoder)

最终结果应该接受我们的输入,对其进行编码,并将结果解码为十进制对象。在

回答我自己的问题。 我输出由特殊字符`包围的十进制对象。然后从文本中删除它和双引号。在

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return '`'+str(o)+'`' #` is special, will be removed later
        return super(DecimalEncoder, self).default(o)

json.dumps(y, cls=DecimalEncoder).replace("\"`",'').replace("`\"",'')

相关问题 更多 >

    热门问题