Open In App

Python Json Serialize A Decimal Object

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JSON (JavaScript Object Notation) is a widely used data interchange format due to its simplicity and readability. When working with Python, it’s common to encounter situations where you must serialize Decimal objects to JSON. The decimal module in Python provides a way to handle decimal numbers with arbitrary precision. In this article, we’ll explore how to serialize Decimal objects to JSON using Python with three different approaches.

Python Json Serialize A Decimal Object

Below are some approaches to perform JSON Serialize A Decimal Object in Python:

  • Basic Serialization with Default Argument
  • Custom JSON Encoder for Decimal Serialization

Json Serialize A Decimal Object Using Basic Serialization with Default Argument

One way to serialize Decimal objects to JSON is by using the default argument of the json.dumps() function. This argument allows us to specify a function that will be called for objects that are not serializable by default. We can use this function to convert Decimal objects to their string representation. In this example, the decimal_serializer function checks if the object is a Decimal. The function converts it to a string using str() if it is. Otherwise, a TypeError is raised.

Python3




import json
from decimal import Decimal
 
# Decimal object
decimal_number = Decimal('123.456')
# Define a custom serialization function
 
def decimal_serializer(obj):
    if isinstance(obj, Decimal):
        return str(obj)
    raise TypeError("Type not serializable")
 
# Serialize the Decimal object using custom serializer
json_data = json.dumps(decimal_number, default=decimal_serializer)
print(type(decimal_number))
print(type(json_data))
print(json_data)


Output

<class 'decimal.Decimal'>
<class 'str'>
"123.456"

Json Serialize A Decimal Object Using Custom JSON Encoder for Decimal Serialization

In this approach, create a custom JSON encoder class that extends the json.JSONEncoder class and overrides its default() method. This method is called for objects that are not natively serializable. In this example, the DecimalEncoder class extends json.JSONEncoder, and its default() method handle the serialization of Decimal objects.

Python3




import json
from decimal import Decimal
 
# Decimal object
decimal_number = Decimal('123.456')
 
# Custom JSON Encoder class
 
class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return str(obj)
        return super().default(obj)
 
# Serialize the Decimal object using custom JSON encoder
json_data = json.dumps(decimal_number, cls=DecimalEncoder)
print(type(decimal_number))
print(type(json_data))
print(json_data)


Output

<class 'decimal.Decimal'>
<class 'str'>
"123.456"

Conclusion

In conclusion, serializing Decimal objects to JSON in Python involves either using the default argument of json.dumps() with a custom serialization function or creating a custom JSON encoder class. Choose the method that best fits your use case, and you’ll be able to seamlessly work with Decimal objects in JSON representations.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads