How to JSON serialize a Decimal object with Python?

Sometimes, we want to JSON serialize a Decimal object with Python.

In this article, we’ll look at how to JSON serialize a Decimal object with Python.

How to JSON serialize a Decimal object with Python?

To JSON serialize a Decimal object with Python, we can use the json.dumps method from the simplejson module with use_decimal set to True.

To install it, we run:

pip install simplejson 

For instance, we write:

import simplejson as json
from decimal import Decimal

s = json.dumps(Decimal('3.9'), use_decimal=True)
print(s)

We use the Decimal constructor to create a decimal number object.

Then we call json.dumps from the simplejson module to convert the decimal number object to a number string.

Conclusion

To JSON serialize a Decimal object with Python, we can use the json.dumps method from the simplejson module with use_decimal set to True.