python
type_error
ai_generated
true
TypeError: 类型 'User' 的对象不是 JSON 可序列化的
TypeError: Object of type 'User' is not JSON serializable
ID: python/fastapi-typeerror-object-of-type-type-is-not-json-serializable
80%修复率
87%置信度
0证据数
2024-03-30首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
直接从端点返回自定义 Python 对象,而未转换为 JSON 可序列化格式。
English
Returning a custom Python object directly from an endpoint without converting to a JSON-serializable format.
解决方案
-
95% 成功率 Use a Pydantic model for the response.
from pydantic import BaseModel class UserOut(BaseModel): id: int name: str @app.get('/users/{user_id}', response_model=UserOut) async def get_user(user_id: int): user = get_user_from_db(user_id) return UserOut(id=user.id, name=user.name) -
90% 成功率 Convert the object to a dictionary manually.
@app.get('/users/{user_id}') async def get_user(user_id: int): user = get_user_from_db(user_id) return {'id': user.id, 'name': user.name}
无效尝试
常见但无效的做法:
-
Using json.dumps() on the object directly.
70% 失败
json.dumps() also requires a serializable object; custom objects need a custom encoder.
-
Returning the object without a response model.
80% 失败
FastAPI tries to serialize the object automatically but fails if it's not a dict or Pydantic model.