Python to JSON Serialization fails on Decimal [duplicate] Python to JSON Serialization fails on Decimal [duplicate] json json

Python to JSON Serialization fails on Decimal [duplicate]


It is not (no longer) recommended you create a subclass; the json.dump() and json.dumps() functions take a default function:

def decimal_default(obj):    if isinstance(obj, decimal.Decimal):        return float(obj)    raise TypeErrorjson.dumps({'x': decimal.Decimal('5.5')}, default=decimal_default)

Demo:

>>> def decimal_default(obj):...     if isinstance(obj, decimal.Decimal):...         return float(obj)...     raise TypeError... >>> json.dumps({'x': decimal.Decimal('5.5')}, default=decimal_default)'{"x": 5.5}'

The code you found only worked on Python 2.6 and overrides a private method that is no longer called in later versions.


I can't believe that no one here talked about using simplejson, which supports deserialization of Decimal out of the box.

import simplejsonfrom decimal import Decimalsimplejson.dumps({"salary": Decimal("5000000.00")})'{"salary": 5000000.00}'simplejson.dumps({"salary": Decimal("1.1")+Decimal("2.2")-Decimal("3.3")})'{"salary": 0.0}'


If you're using Django. There is a great class for Decimal and date fields:

https://docs.djangoproject.com/en/1.10/topics/serialization/#djangojsonencoder

To use it:

import jsonfrom django.core.serializers.json import DjangoJSONEncoderjson.dumps(value, cls=DjangoJSONEncoder)