python type_error ai_generated true

TypeError: Object of type datetime is not JSON serializable

ID: python/flask-jsonify-serialization

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

jsonify() cannot serialize non-JSON-native types such as datetime, Decimal, or custom objects.

generic

中文

jsonify() 无法序列化 datetime、Decimal 或自定义对象等非 JSON 原生类型。

Workarounds

  1. 95% success
    return jsonify({'created': obj.created_at.isoformat()})
  2. 88% success
    from flask.json.provider import DefaultJSONProvider
    class P(DefaultJSONProvider):
        @staticmethod
        def default(o): return o.isoformat()
    app.json = P(app)

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Bypasses Flask's jsonify behavior and content-type handling.

  2. 80% fail

    Hides the real serialization issue from clients.