Python JSON 序列化一个 Decimal 对象 [英] Python JSON serialize a Decimal object

查看:64
本文介绍了Python JSON 序列化一个 Decimal 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 对象,并且预先转换为浮点数会产生 {'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 default(self, o):
        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).default(o)

然后像这样使用它:

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

这篇关于Python JSON 序列化一个 Decimal 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆