python
type_error
ai_generated
true
TypeError: Object of type datetime is not JSON serializable
ID: python/flask-jsonify-datetime-serialization
80%Fix Rate
88%Confidence
0Evidence
2024-01-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
Returning datetime objects directly in JSON responses without custom serializer.
generic中文
在 JSON 响应中直接返回 datetime 对象,未使用自定义序列化器。
Workarounds
-
95% success
from flask import Flask, jsonify from datetime import datetime app = Flask(__name__) @app.route('/time') def time(): return jsonify({'time': datetime.now().isoformat()}) -
90% success
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
Dead Ends
Common approaches that don't work:
-
60% fail
Duplicated code and easy to forget.
-
80% fail
jsonify does not use json.dumps default; need custom encoder.