In this article, we will discuss in detail how to fix “typeerror object of type decimal is not json serializable.”
Encountering this error is usually confusing, especially if you’re new to it.
And doesn’t have any idea on how to troubleshoot this “object of type decimal is not json serializable” type error.
So, to have a clear understanding and to fully fix this error, keep reading!
What is JSON serializable?
A JSON serializable refers to data that can be converted to a JSON format without any issues.
JSON stands for JavaScript Object Notation.
JSON is a widely used format for data exchange, particularly in web applications.
It can represent simple data types such as strings and numbers, as well as complex data types such as lists and dictionaries.
However, not all Python objects can be directly serialized to JSON.
If you encounter this error message, it means that you are attempting to convert an object of an unsupported type to JSON.
You’ll see in the table below how the native Python objects are translated to JSON.
Python | JSON |
list, tuple | array |
int, long, float | number |
dict | object |
str | string |
None | null |
True | true |
False | false |
What is “typeerror object of type decimal is not json serializable”?
The “typeerror: object of type decimal is not json serializable” is an error message that usually occurs in Python.
It happens when you’re trying to convert a decimal object to JSON format using the built-in JSON module.
However, decimals are not serializable by default, meaning they cannot be converted to a string that represents a JSON object.
Since the JSON module does not have native support for the Decimal type.
For example:
import json
from decimal import Decimal
decimal_value = Decimal('123.4')
json_str = json.dumps({'income': decimal_value})
print(json_str)
As a result, it will throw an error message:
TypeError: Object of type Decimal is not JSON serializable
Why does this error occur?
There are several reasons why this error might occur:
→ One common cause is that the decimal type is not natively supported in JSON, so the JSON serializer doesn’t know how to convert decimal objects to JSON.
→ Another cause is that the decimal object is not being used correctly in the code, such as by passing it as an argument to a JSON serialization function.
How to fix “typeerror object of type decimal is not json serializable”?
To fix this “Python typeerror object of type decimal is not json serializable,” here are the following solutions:
Solution 1: Use default keyword
Set the default keyword argument to str when calling the json.dumps() method.
This will convert the Decimal object to a string.
import json
from decimal import Decimal
decimal_value = Decimal('123.4')
json_str = json.dumps({'income': decimal_value}, default=str)
print(json_str)
print(type(json_str))
Output:
{"income": "123.4"}
<class 'str'>
Solution 2: Define a custom function
Define a custom function that converts a Decimal object to a string and set the default keyword argument to the name of that function.
import json
from decimal import Decimal
def decimal_default(obj):
if isinstance(obj, Decimal):
return str(obj)
raise TypeError
decimal_value = Decimal('123.4')
json_str = json.dumps(decimal_value, default=decimal_default)
print(json_str)
Output:
"123.4"
Solution 3: Use simplejson module
Using the simplejson module is an alternative way to resolve the error.
The simplejson library has built-in support for serializing Decimal objects.
You can install the simplejson module using the following command:
pip install simplejson
or
pip3 install simplejson
Then you can run your code smoothly just like the example below”
import simplejson as json
from decimal import Decimal
decimal_value = Decimal('123.4')
json_str = json.dumps({'income': decimal_value}, use_decimal=True)
print(json_str)
Output:
123.4
Solution 4: Use JSONEncoder class
Subclass the JSONEncoder class and override its default method to handle Decimal objects.
import json
from decimal import Decimal
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return str(obj)
return super().default(obj)
decimal_value = Decimal('123.4')
json_str = json.dumps(decimal_value, cls=DecimalEncoder)
print(json_str)
Output:
"123.4"
Solution 5: Converting decimal objects to float
Convert the Decimal object to a float before serializing it. However, keep in mind that this may result in a loss of precision.
import json
from decimal import Decimal
decimal_value = Decimal('123.4')
json_str = json.dumps(float(decimal_value))
print(json_str)
Output:
123.4
Conclusion
This article already provides different solutions that you may use to fix this “typeerror object of type decimal is not json serializable” error message in Python.
We are hoping that this article provided you with sufficient solutions to get rid of the error.
You could also check out other “typeerror” articles that may help you in the future if you encounter them.
- Typeerror not supported between instances of nonetype and int
- Typeerror object of type series is not json serializable
- Typeerror numpy.ndarray object is not callable
Thank you very much for reading to the end of this article.