python type_error ai_generated true

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

TypeError: Object of type datetime is not JSON serializable

ID: python/flask-jsonify-datetime-serialization

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

版本兼容性

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

根因分析

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

English

Returning datetime objects directly in JSON responses without custom serializer.

generic

解决方案

  1. 95% 成功率
    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% 成功率
    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

无效尝试

常见但无效的做法:

  1. 60% 失败

    Duplicated code and easy to forget.

  2. 80% 失败

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