python type_error ai_generated true

TypeError: datetime 类型对象不可 JSON 序列化。

TypeError: Object of type datetime is not JSON serializable

ID: python/flask-jsonify-not-serializable

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

版本兼容性

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

根因分析

jsonify(或响应)序列化包含 datetime、Decimal、UUID 或未注册 JSON 编码器的自定义类的对象。

English

jsonify (or response) attempted to serialize an object containing datetime, Decimal, UUID, or a custom class without a JSON encoder.

generic

解决方案

  1. 95% 成功率
    Custom encoder:
    class CustomJSONProvider(DefaultJSONProvider):
        @staticmethod
        def default(o):
            if isinstance(o, datetime): return o.isoformat()
            return super().default(o)
    app.json = CustomJSONProvider(app)
  2. 90% 成功率
    Or convert before returning: `return jsonify({'created': user.created_at.isoformat()})`

无效尝试

常见但无效的做法:

  1. 90% 失败

    Produces `"<__main__.User object at 0x...>"`, useless to clients.

  2. 95% 失败

    Breaks jsonify entirely.