Python Json Encode Decimal

July 26, 2019
import json
import decimal

class JsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            return float(obj)
        return json.JSONEncoder.default(self, obj)


data = {
    'float': 7.5,
    'decimal': decimal.Decimal(7.5)
}
json.dumps(data, indent=2, cls=JsonEncoder)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.