python type_error ai_generated true

TypeError: Object of type 'Decimal' is not JSON serializable

ID: python/flask-jsonify-error-nonserializable

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Flask's jsonify uses default JSON encoder which cannot serialize Decimal.

generic

中文

Flask的jsonify使用默认JSON编码器,无法序列化Decimal。

Workarounds

  1. 90% success Create a custom JSON encoder and set it on the Flask app.
    from flask import Flask, jsonify
    from json import JSONEncoder
    class CustomEncoder(JSONEncoder):
        def default(self, obj):
            if isinstance(obj, Decimal):
                return str(obj)
            return super().default(obj)
    app = Flask(__name__)
    app.json_encoder = CustomEncoder
  2. 85% success Convert Decimal to string in the data before jsonify.
    data = {'price': str(decimal_value)}
    return jsonify(data)

Dead Ends

Common approaches that don't work:

  1. Converting Decimal to float manually, losing precision. 60% fail

    Float may introduce rounding errors for financial data.

  2. Using json.dumps with default=str but not integrating with jsonify. 70% fail

    jsonify does not use the same encoder as json.dumps by default.