TypeError: Object of type Decimal is not JSON serializable

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: Object of type Decimal is not JSON serializable #

The Python "TypeError: Object of type Decimal is not JSON serializable" occurs when we try to convert a Decimal to a JSON string. To solve the error, extend the JSONEncoder class and convert the decimal to a string to preserve its precision.

Here is an example of how the error occurs.

main.py
import json from decimal import * num = Decimal('3.14') # ⛔️ TypeError: Object of type Decimal is not JSON serializable json_str = json.dumps({'salary': num})

We tried passing a Decimal to the json.dumps() method but the method doesn't handle Decimal values by default.

To solve the error, extend from the JSONEncoder class and convert Decimal values to a string when serializing them.

main.py
import json from decimal import * num = Decimal('3.14') class DecimalEncoder(json.JSONEncoder): def default(self, obj): # 👇️ if passed in object is instance of Decimal # convert it to a string if isinstance(obj, Decimal): return str(obj) # 👇️ otherwise use the default behavior return json.JSONEncoder.default(self, obj) json_str = json.dumps({'salary': num}, cls=DecimalEncoder) print(json_str) # 👉️ '{"salary": "3.14"}' print(type(json_str)) # 👉️ <class 'str'>

The json.dumps method converts a Python object to a JSON formatted string.

We extended from the JSONEncoder class.

The JSONEncoder class supports the following objects and types by default.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

Notice that the JSONEncoder class doesn't support Decimal to JSON conversion by default.

We can handle this by extending from the class and implementing a default() method that returns a serializable object.

main.py
import json from decimal import * class DecimalEncoder(json.JSONEncoder): def default(self, obj): # 👇️ if passed in object is instance of Decimal # convert it to a string if isinstance(obj, Decimal): return str(obj) # 👇️ otherwise use the default behavior return json.JSONEncoder.default(self, obj)
In our if statement, we check if the passed in object is an instance of the Decimal class and if it is, we convert it to a string and return the result.

In all other cases, we let the base class's default method do the serialization.

To use a custom JSONEncoder, specify it with the cls keyword argument in your call to the json.dumps() method.

main.py
import json from decimal import * num = Decimal('3.14') class DecimalEncoder(json.JSONEncoder): def default(self, obj): # 👇️ if passed in object is instance of Decimal # convert it to a string if isinstance(obj, Decimal): return str(obj) # 👇️ otherwise use the default behavior return json.JSONEncoder.default(self, obj) # ✅ set cls kwarg json_str = json.dumps({'salary': num}, cls=DecimalEncoder) print(json_str) # 👉️ {"salary": "3.14"} print(type(json_str)) # 👉️ <class 'str'>

If you don't provide the cls kwarg, the default JSONEncoder is used.

Conclusion #

The Python "TypeError: Object of type Decimal is not JSON serializable" occurs when we try to convert a Decimal to a JSON string. To solve the error, extend the JSONEncoder class and convert the decimal to a string to preserve its precision.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.