python type_error ai_generated true

TypeError: Object of type datetime is not JSON serializable

ID: python/fastapi-jsonable-encoder-datetime

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-04-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Easy to miss; inconsistent formats across endpoints.

  2. 90% fail

    Not interoperable with browsers and unsafe.