python
type_error
ai_generated
true
类型错误:类型为 'Decimal' 的对象不可JSON序列化
TypeError: Object of type 'Decimal' is not JSON serializable
ID: python/flask-jsonify-error-nonserializable
80%修复率
85%置信度
0证据数
2025-07-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
Flask的jsonify使用默认JSON编码器,无法序列化Decimal。
English
Flask's jsonify uses default JSON encoder which cannot serialize Decimal.
解决方案
-
90% 成功率 Create a custom JSON encoder and set it on the Flask app.
from flask import Flask, jsonify from json import JSONEncoder class CustomEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return str(obj) return super().default(obj) app = Flask(__name__) app.json_encoder = CustomEncoder -
85% 成功率 Convert Decimal to string in the data before jsonify.
data = {'price': str(decimal_value)} return jsonify(data)
无效尝试
常见但无效的做法:
-
Converting Decimal to float manually, losing precision.
60% 失败
Float may introduce rounding errors for financial data.
-
Using json.dumps with default=str but not integrating with jsonify.
70% 失败
jsonify does not use the same encoder as json.dumps by default.