python type_error ai_generated true

TypeError: Object of type Decimal is not JSON serializable

ID: python/flask-jsonify-error-non-serializable

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2025-04-08First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active
3.10 active

Root Cause

Flask 的 jsonify 函数无法序列化 Decimal 类型数据

generic

中文

Flask 的 jsonify 函数无法序列化 Decimal 类型数据

Workarounds

  1. 95% success 自定义 JSON 编码器
    from flask import Flask, jsonify
    from decimal import Decimal
    class CustomJSONEncoder(JSONEncoder):
        def default(self, obj):
            if isinstance(obj, Decimal):
                return float(obj)
            return super().default(obj)
    app.json_encoder = CustomJSONEncoder
  2. 90% success 手动转换为 float 或 str
    data = {'price': float(decimal_value)}

Dead Ends

Common approaches that don't work:

  1. 使用 str() 转换但丢失精度 60% fail

    Decimal 精度可能丢失

  2. 使用 json.dumps 替代 jsonify 70% fail

    Flask 响应需要特定格式