小编典典

Python JSON序列化Decimal对象

json

我有一个Decimal('3.9')对象的一部分,希望将其编码为JSON字符串,看起来像{'x': 3.9}。我不在乎客户端的精度,因此浮点数很好。

有一个好的方法可以将此序列化吗?JSONDecoder不接受Decimal对象,并且事先转换为float会产生{'x': 3.8999999999999999}错误,这将浪费大量带宽。


阅读 428

收藏
2020-07-27

共1个答案

小编典典

子类化如何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)
2020-07-27