python type_error ai_generated true

TypeError: Object of type datetime is not JSON serializable

ID: python/flask-jsonify-not-serializable

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2025-08-19First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —
3.x active — — —

Root Cause

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

generic

中文

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

Workarounds

  1. 95% success
    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% success
    Or convert before returning: `return jsonify({'created': user.created_at.isoformat()})`

Dead Ends

Common approaches that don't work:

  1. 90% fail

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

  2. 95% fail

    Breaks jsonify entirely.