python type_error ai_generated true

TypeError: Object of type datetime is not JSON serializable

ID: python/starlette-json-response-non-serializable

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-09-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

在 Starlette 的 JSONResponse 中直接返回了 datetime 对象,而标准 JSON 序列化不支持该类型。

generic

中文

在 Starlette 的 JSONResponse 中直接返回了 datetime 对象,而标准 JSON 序列化不支持该类型。

Workarounds

  1. 95% success
    data = {'time': datetime.now().isoformat()}
    return JSONResponse(data)
  2. 90% success
    from starlette.responses import JSONResponse
    class CustomJSONResponse(JSONResponse):
        def render(self, content):
            return json.dumps(content, default=str).encode()

Dead Ends

Common approaches that don't work:

  1. 60% fail

    虽然能序列化,但格式不可控,前端解析困难。

  2. 80% fail

    Starlette 的 JSONResponse 不接受自定义序列化器,此方法无效。