python
type_error
ai_generated
true
TypeError: Object of type 'datetime' is not JSON serializable
ID: python/flask-jsonify-serialization-error
80%Fix Rate
88%Confidence
0Evidence
2024-12-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
尝试将 datetime 对象直接传递给 jsonify()。
generic中文
尝试将 datetime 对象直接传递给 jsonify()。
Workarounds
-
95% success
from flask.json import JSONEncoder class CustomJSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() return super().default(obj) app.json_encoder = CustomJSONEncoder
Dead Ends
Common approaches that don't work:
-
60% fail
会丢失日期格式,且不适用于所有情况
-
90% fail
同样无法序列化 datetime