python
type_error
ai_generated
true
TypeError: Object of type ObjectId is not JSON serializable
ID: python/fastapi-jsonable-encoder-error
80%Fix Rate
83%Confidence
0Evidence
2024-07-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
Returning MongoDB ObjectId or similar BSON types directly from a FastAPI route without converting them.
generic中文
在FastAPI路由中直接返回MongoDB ObjectId或类似的BSON类型,而没有进行转换。
Workarounds
-
90% success
Use Pydantic's Json type: from pydantic import Json\nclass Item(BaseModel):\n id: Json[Any]
-
95% success
Convert ObjectId to str in the route: item['_id'] = str(item['_id'])
Dead Ends
Common approaches that don't work:
-
60% fail
Converting ObjectId to str manually works but loses the original type information.
-
70% fail
Using json.dumps with a custom default function may not integrate with FastAPI's response model.