python
type_error
ai_generated
true
TypeError: 类型为 UUID 的对象无法 JSON 序列化
TypeError: Object of type UUID is not JSON serializable
ID: python/fastapi-json-encoding-error
80%修复率
87%置信度
0证据数
2024-09-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
FastAPI 的默认 JSON 编码器无法处理响应中的 UUID 对象。
English
FastAPI's default JSON encoder cannot handle UUID objects in the response.
解决方案
-
90% 成功率
Use jsonable_encoder: from fastapi.encoders import jsonable_encoder; return jsonable_encoder(data)
-
85% 成功率
Define a custom response class that handles UUIDs: class UUIDModel(BaseModel): id: UUID
无效尝试
常见但无效的做法:
-
60% 失败
This is repetitive and error-prone if missed in some places.
-
50% 失败
If imported incorrectly, it may not convert UUIDs.