python type_error ai_generated true

类型错误:datetime 类型的对象无法进行 JSON 序列化

TypeError: Object of type datetime is not JSON serializable

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

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

版本兼容性

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

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 60% 失败

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

  2. 80% 失败

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