python type_error ai_generated true

TypeError: datetime 类型的对象不可 JSON 序列化

TypeError: Object of type datetime is not JSON serializable

ID: python/flask-jsonify-serialization

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

版本兼容性

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

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 60% 失败

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

  2. 80% 失败

    Hides the real serialization issue from clients.