python type_error ai_generated true

类型错误:datetime类型的对象无法JSON序列化

TypeError: Object of type datetime is not JSON serializable

ID: python/flask-jsonify-serialization-error

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2024-04-18首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

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

English

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

解决方案

  1. 95% 成功率
    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% 成功率
    Convert datetime to ISO format manually: return jsonify({'time': datetime.now().isoformat()})

无效尝试

常见但无效的做法:

  1. 50% 失败

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

  2. 40% 失败

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