python
type_error
ai_generated
true
TypeError: Object of type Decimal is not JSON serializable
ID: python/flask-jsonify-error-non-serializable
80%Fix Rate
85%Confidence
0Evidence
2025-04-08First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
Root Cause
Flask 的 jsonify 函数无法序列化 Decimal 类型数据
generic中文
Flask 的 jsonify 函数无法序列化 Decimal 类型数据
Workarounds
-
95% success 自定义 JSON 编码器
from flask import Flask, jsonify from decimal import Decimal class CustomJSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return float(obj) return super().default(obj) app.json_encoder = CustomJSONEncoder -
90% success 手动转换为 float 或 str
data = {'price': float(decimal_value)}
Dead Ends
Common approaches that don't work:
-
使用 str() 转换但丢失精度
60% fail
Decimal 精度可能丢失
-
使用 json.dumps 替代 jsonify
70% fail
Flask 响应需要特定格式