python
type_error
ai_generated
true
类型错误:ObjectId类型的对象无法JSON序列化
TypeError: Object of type ObjectId is not JSON serializable
ID: python/fastapi-jsonable-encoder-error
80%修复率
83%置信度
0证据数
2024-07-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
在FastAPI路由中直接返回MongoDB ObjectId或类似的BSON类型,而没有进行转换。
English
Returning MongoDB ObjectId or similar BSON types directly from a FastAPI route without converting them.
解决方案
-
90% 成功率
Use Pydantic's Json type: from pydantic import Json\nclass Item(BaseModel):\n id: Json[Any]
-
95% 成功率
Convert ObjectId to str in the route: item['_id'] = str(item['_id'])
无效尝试
常见但无效的做法:
-
60% 失败
Converting ObjectId to str manually works but loses the original type information.
-
70% 失败
Using json.dumps with a custom default function may not integrate with FastAPI's response model.