python
data_error
ai_generated
true
TypeError: Object of type datetime is not JSON serializable
ID: python/fastapi-json-encode-error
80%Fix Rate
85%Confidence
0Evidence
2024-12-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
Root Cause
FastAPI 路径操作返回了 Python datetime 对象,但 JSON 编码器无法处理
generic中文
FastAPI 路径操作返回了 Python datetime 对象,但 JSON 编码器无法处理
Workarounds
-
95% success 使用 Pydantic 模型并定义字段类型
from pydantic import BaseModel class Item(BaseModel): created_at: datetime class Config: json_encoders = {datetime: lambda v: v.isoformat()} -
90% success 在返回前手动转换
return {'created_at': datetime.now().isoformat()}
Dead Ends
Common approaches that don't work:
-
手动将 datetime 转为字符串但忽略时区
60% fail
可能导致时区信息丢失
-
使用 json.dumps 并设置默认参数
70% fail
FastAPI 使用自己的 JSON 编码器,自定义可能被覆盖