文章内容

2019/5/19 17:56:33,作 者: 黄兵

Object of type 'Decimal' is not JSON serializable

最近使用Flask.jsonify()的时候出现如下错误:

Object of type 'Decimal' is not JSON serializable


出现问题的原因:

jsonify()无法处理Decimal数据类型。


解决方案:

您可以通过在应用json_encoder程序实例上设置属性来覆盖应用程序的JSON编码器:

import flask

app = flask.Flask(...)
app.json_encoder = MyJSONEncoder

然后你可以对Flask进行子类化JSONEncoder并覆盖该default()方法以提供对其他类型的支持:

import decimal
import flask.json

class MyJSONEncoder(flask.json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            # Convert decimal instances to strings.
            return str(obj)
        return super(MyJSONEncoder, self).default(obj)


参考资料:

1、How to convert all Decimals in a Python data structure to string?

分享到:

发表评论

评论列表

user-ico

叶卿卿 on 回复 有用(0

这个是编程吗?好羡慕好厉害哦

游客Q1gv on 2019-05-24 16:55:01

博主回复:是的,没有呐 :)O(∩_∩)O~