python
type_error
ai_generated
true
TypeError: Object of type 'Decimal' is not JSON serializable
ID: python/flask-jsonify-error-nonserializable
80%Fix Rate
85%Confidence
0Evidence
2025-07-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
Flask's jsonify uses default JSON encoder which cannot serialize Decimal.
generic中文
Flask的jsonify使用默认JSON编码器,无法序列化Decimal。
Workarounds
-
90% success 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% success Convert Decimal to string in the data before jsonify.
data = {'price': str(decimal_value)} return jsonify(data)
Dead Ends
Common approaches that don't work:
-
Converting Decimal to float manually, losing precision.
60% fail
Float may introduce rounding errors for financial data.
-
Using json.dumps with default=str but not integrating with jsonify.
70% fail
jsonify does not use the same encoder as json.dumps by default.