python
type_error
ai_generated
true
TypeError: datetime 类型对象不可 JSON 序列化。
TypeError: Object of type datetime is not JSON serializable
ID: python/flask-jsonify-not-serializable
80%修复率
88%置信度
0证据数
2025-08-19首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
| 3.x | active | — | — | — |
根因分析
jsonify(或响应)序列化包含 datetime、Decimal、UUID 或未注册 JSON 编码器的自定义类的对象。
English
jsonify (or response) attempted to serialize an object containing datetime, Decimal, UUID, or a custom class without a JSON encoder.
解决方案
-
95% 成功率
Custom encoder: class CustomJSONProvider(DefaultJSONProvider): @staticmethod def default(o): if isinstance(o, datetime): return o.isoformat() return super().default(o) app.json = CustomJSONProvider(app) -
90% 成功率
Or convert before returning: `return jsonify({'created': user.created_at.isoformat()})`
无效尝试
常见但无效的做法:
-
90% 失败
Produces `"<__main__.User object at 0x...>"`, useless to clients.
-
95% 失败
Breaks jsonify entirely.