python type_error ai_generated true

TypeError: Object of type 'datetime' is not JSON serializable

ID: python/flask-jsonify-serialization-error

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

尝试将 datetime 对象直接传递给 jsonify()。

generic

中文

尝试将 datetime 对象直接传递给 jsonify()。

Workarounds

  1. 95% success
    from flask.json import 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

    会丢失日期格式,且不适用于所有情况

  2. 90% fail

    同样无法序列化 datetime