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
87%Confidence
0Evidence
2024-04-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Returning a datetime or other non-serializable object directly from a Flask route without converting it to a string or using a custom encoder.

generic

中文

在Flask路由中直接返回datetime或其他不可序列化的对象,而没有转换为字符串或使用自定义编码器。

Workarounds

  1. 95% success
    Define a custom JSON encoder: class CustomEncoder(json.JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, datetime):\n            return obj.isoformat()\n        return super().default(obj)\napp.json_encoder = CustomEncoder
  2. 90% success
    Convert datetime to ISO format manually: return jsonify({'time': datetime.now().isoformat()})

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Using str(datetime) converts to a string but loses formatting and may cause inconsistent output.

  2. 40% fail

    Setting app.json_encoder = None does not fix the issue and may break other serialization.