Python JSON序列化Decimal对象

Python JSON序列化Decimal对象

问题描述:

我有一个Decimal('3.9')作为对象的一部分,希望将其编码为一个看起来像{'x': 3.9}的JSON字符串.我不在乎客户端的精度,所以浮点数就可以了.

I have a Decimal('3.9') as part of an object, and wish to encode this to a JSON string which should look like {'x': 3.9}. I don't care about precision on the client side, so a float is fine.

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

Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, and converting to a float beforehand yields {'x': 3.8999999999999999} which is wrong, and will be a big waste of bandwidth.

子类化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)