python
type_error
ai_generated
true
TypeError: Object of type datetime is not JSON serializable
ID: python/starlette-json-response-non-serializable
80%Fix Rate
87%Confidence
0Evidence
2024-09-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
在 Starlette 的 JSONResponse 中直接返回了 datetime 对象,而标准 JSON 序列化不支持该类型。
generic中文
在 Starlette 的 JSONResponse 中直接返回了 datetime 对象,而标准 JSON 序列化不支持该类型。
Workarounds
-
95% success
data = {'time': datetime.now().isoformat()} return JSONResponse(data) -
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:
-
60% fail
虽然能序列化,但格式不可控,前端解析困难。
-
80% fail
Starlette 的 JSONResponse 不接受自定义序列化器,此方法无效。