python
type_error
ai_generated
true
类型错误:datetime 类型的对象无法 JSON 序列化。
TypeError: Object of type datetime is not JSON serializable
ID: python/flask-jsonify-datetime-serialization
80%修复率
88%置信度
0证据数
2024-01-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
在 JSON 响应中直接返回 datetime 对象,未使用自定义序列化器。
English
Returning datetime objects directly in JSON responses without custom serializer.
解决方案
-
95% 成功率
from flask import Flask, jsonify from datetime import datetime app = Flask(__name__) @app.route('/time') def time(): return jsonify({'time': datetime.now().isoformat()}) -
90% 成功率
Define custom JSONEncoder: class CustomJSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() return super().default(obj) app.json_encoder = CustomJSONEncoder
无效尝试
常见但无效的做法:
-
60% 失败
Duplicated code and easy to forget.
-
80% 失败
jsonify does not use json.dumps default; need custom encoder.