Python 3.x无法将Decimal()序列化为JSON [英] Python 3.x cannot serialize Decimal() to JSON

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

问题描述

我早些时候问过这个问题,它被标记为的重复项,但是接受的答案不起作用,并且甚至pylint也表明代码中有错误.

I asked this question earlier, and it was marked as duplicate of this, but the accepted answer does not work and even pylint shows that there are errors in the code.

我想做什么:

from decimal import Decimal
import json

thang = {
    'Items': [{'contact_id': Decimal('2'), 'street_name': 'Asdasd'}, {'contact_id': Decimal('1'), 'name': 'Lukas', 'customer_id': Decimal('1')}],
     'Count': 2}

print(json.dumps(thang))

这引发: TypeError: Object of type 'Decimal' is not JSON serializable

所以我尝试了链接的答案:

from decimal import Decimal
import json

thang = {
    'Items': [{'contact_id': Decimal('2'), 'street_name': 'Asdasd'}, {'contact_id': Decimal('1'), 'name': 'Lukas', 'customer_id': Decimal('1')}],
     'Count': 2}


class DecimalEncoder(json.JSONEncoder):
    def _iterencode(self, o, markers=None):
        if isinstance(o, 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)


print(json.dumps(thang, cls=DecimalEncoder))

这里的linter显示行return super(DecimalEncoder, self)._iterencode(o, markers)有错误,因为Super of 'DecimalEncoder' has no '_iterencode' member和运行时抛出 TypeError: Object of type 'Decimal' is not JSON serializable

And here the linter shows that line return super(DecimalEncoder, self)._iterencode(o, markers) has errors, because Super of 'DecimalEncoder' has no '_iterencode' member and when ran throws TypeError: Object of type 'Decimal' is not JSON serializable

我如何进行这项工作?

推荐答案

该答案被证明已经过时,还有另一个 answer 以及有效的解决方案:

That answer turned out to be outdated and there was another answer with the working solution:

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

这篇关于Python 3.x无法将Decimal()序列化为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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