Python flask TypeError: Object of type ‘Decimal’ is not JSON serializable

导入 simplejson 包

不改动代码的情况下, 快速解决:

pip install  simplejson

自定义Jsonify的Json编码

也可以自己封装一下:

import decimal

from flask import current_app as app
from flask import Jsonify
from flask.json import JSONEncoder

class JsonEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            return float(obj)
        return JSONEncoder.default(self, obj)

@app.route('/test_jsonify')
def test_jsonify():
    data = {
        'float': 7.5,
        'decimal': decimal.Decimal(7.5)
    }

    app.json_encoder = JsonEncoder
    return jsonify(data)

参考:



blog comments powered by Disqus

Published

15 November 2022

Tags