python type_error ai_generated true

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

TypeError: Object of type datetime is not JSON serializable

ID: python/fastapi-jsonable-encoder-datetime

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-04-15首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

在 JSONResponse 中直接返回 datetime(而非 Pydantic 模型),绕过了 FastAPI 的编码器;json.dumps 无法处理 datetime。

English

Returning a raw datetime in a JSONResponse (not a Pydantic model) bypasses FastAPI's encoder; json.dumps cannot handle datetime.

generic

解决方案

  1. 93% 成功率
    from fastapi.encoders import jsonable_encoder; return JSONResponse(jsonable_encoder(obj))
  2. 90% 成功率
    Return a Pydantic model with datetime field; FastAPI serializes it

无效尝试

常见但无效的做法:

  1. 50% 失败

    Easy to miss; inconsistent formats across endpoints.

  2. 90% 失败

    Not interoperable with browsers and unsafe.