python type_error ai_generated true

TypeError: Object of type datetime is not JSON serializable

ID: python/flask-jsonify-datetime-serialization

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-01-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Returning datetime objects directly in JSON responses without custom serializer.

generic

中文

在 JSON 响应中直接返回 datetime 对象,未使用自定义序列化器。

Workarounds

  1. 95% success
    from flask import Flask, jsonify
    from datetime import datetime
    
    app = Flask(__name__)
    
    @app.route('/time')
    def time():
        return jsonify({'time': datetime.now().isoformat()})
  2. 90% success
    Define custom JSONEncoder: class CustomJSONEncoder(JSONEncoder):
        def default(self, obj):
            if isinstance(obj, datetime):
                return obj.isoformat()
            return super().default(obj)
    app.json_encoder = CustomJSONEncoder

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Duplicated code and easy to forget.

  2. 80% fail

    jsonify does not use json.dumps default; need custom encoder.