python
type_error
ai_generated
true
TypeError: Object of type datetime is not JSON serializable
ID: python/fastapi-jsonable-encoder-datetime
80%Fix Rate
88%Confidence
0Evidence
2024-04-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
Returning a raw datetime in a JSONResponse (not a Pydantic model) bypasses FastAPI's encoder; json.dumps cannot handle datetime.
generic中文
在 JSONResponse 中直接返回 datetime(而非 Pydantic 模型),绕过了 FastAPI 的编码器;json.dumps 无法处理 datetime。
Workarounds
-
93% success
from fastapi.encoders import jsonable_encoder; return JSONResponse(jsonable_encoder(obj))
-
90% success
Return a Pydantic model with datetime field; FastAPI serializes it
Dead Ends
Common approaches that don't work:
-
50% fail
Easy to miss; inconsistent formats across endpoints.
-
90% fail
Not interoperable with browsers and unsafe.