python type_error ai_generated true

TypeError: 类型为 UUID 的对象无法 JSON 序列化

TypeError: Object of type UUID is not JSON serializable

ID: python/fastapi-json-encoding-error

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 90% 成功率
    Use jsonable_encoder: from fastapi.encoders import jsonable_encoder; return jsonable_encoder(data)
  2. 85% 成功率
    Define a custom response class that handles UUIDs: class UUIDModel(BaseModel): id: UUID

无效尝试

常见但无效的做法:

  1. 60% 失败

    This is repetitive and error-prone if missed in some places.

  2. 50% 失败

    If imported incorrectly, it may not convert UUIDs.