python type_error ai_generated true

类型错误:ObjectId类型的对象无法JSON序列化

TypeError: Object of type ObjectId is not JSON serializable

ID: python/fastapi-jsonable-encoder-error

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

generic

解决方案

  1. 90% 成功率
    Use Pydantic's Json type: from pydantic import Json\nclass Item(BaseModel):\n    id: Json[Any]
  2. 95% 成功率
    Convert ObjectId to str in the route: item['_id'] = str(item['_id'])

无效尝试

常见但无效的做法:

  1. 60% 失败

    Converting ObjectId to str manually works but loses the original type information.

  2. 70% 失败

    Using json.dumps with a custom default function may not integrate with FastAPI's response model.