python
type_error
ai_generated
true
TypeError: datetime 类型的对象无法 JSON 序列化
TypeError: Object of type datetime is not JSON serializable
ID: python/fastapi-jsonable-encoder-datetime
80%修复率
88%置信度
0证据数
2024-04-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
在 JSONResponse 中直接返回 datetime(而非 Pydantic 模型),绕过了 FastAPI 的编码器;json.dumps 无法处理 datetime。
English
Returning a raw datetime in a JSONResponse (not a Pydantic model) bypasses FastAPI's encoder; json.dumps cannot handle datetime.
解决方案
-
93% 成功率
from fastapi.encoders import jsonable_encoder; return JSONResponse(jsonable_encoder(obj))
-
90% 成功率
Return a Pydantic model with datetime field; FastAPI serializes it
无效尝试
常见但无效的做法:
-
50% 失败
Easy to miss; inconsistent formats across endpoints.
-
90% 失败
Not interoperable with browsers and unsafe.