TypeError: Object of type Decimal is not JSON serializable

Are you getting the error “typeerror: object of type decimal is not json serializable“? Yes, you have come to the right place. Today, I will show you how to solve this error. This error occurs when we try to convert a decimal to a JSON string.

[Fixed] TypeError: Object of type Decimal is not JSON serializable

You can solve this error by using the ‘JSONEncoder‘ class to convert the decimal to JSON string to preserve its precision.

This error occurs in the code below:

import json
from decimal import *

my_gpa = Decimal('3.14')

# TypeError: Object of type Decimal is not JSON serializable
str_json = json.dumps({'GPA': my_gpa})

In the above code, we are trying to convert the decimal to a JSON string but are getting an error. because we can’t directly pass the decimal to ‘json.dumps‘.

[Fixed]: TypeError: Object of type bytes is not JSON serializable

We can solve this error by using the JSONEncoder class. Below is the code to get rid of the error.

import json
from decimal import *

my_gpa= Decimal('3.14')

class DecimalEncoder(json.JSONEncoder):
     def default(self, obj):
        if isinstance(obj, Decimal):
            return str(obj)
        return json.JSONEncoder.default(self, obj)

json_str = json.dumps({'GPA': my_gpa}, cls=DecimalEncoder)

print(json_str)     #OUTPUT --> {"salary": "3.14"}
print(type(json_str))     #OUTPUT --> <class 'str'>

JSONEncoder class supported objects and types:

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.

import json
from decimal import *

class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):

        if isinstance(obj, Decimal):
            return str(obj)
        return json.JSONEncoder.default(self, obj)

Conclusion: typeerror object of type decimal is not json serializable

Guys, we discussed how we can solve this error “typeerror: object of type decimal is not json serializable“. If you are still facing the error please let us know in the comments section. You can solve this error by using the ‘JSONEncoder’ class to convert the decimal to JSON string to preserve its precision.

Leave a Reply