您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python JSON序列化Decimal对象

Python JSON序列化Decimal对象

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

我想让大家知道,我在运行Python 2.6.5的Web服务器上尝试了Micha?Marczyk的答案,并且运行良好。但是,我升级到Python 2.7,并且停止工作。我试图想到一种编码Decimal对象的方法,这就是我想出的:

import decimal

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

希望这应该对任何遇到Python 2.7问题的人有所帮助。我测试了它,它似乎工作正常。如果有人注意到我的解决方案中的任何错误或提出了更好的方法,请告诉我。

python 2022/1/1 18:24:08 有175人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶