Home >Backend Development >Python Tutorial >How Can I Serialize Decimal Objects in Python JSON Without Losing Precision?
Serialization of Decimal Objects in Python JSON
Serializing Decimal objects to JSON presents a challenge due to the lack of support for Decimal objects in JSONDecoder. Converting Decimal objects to floats can result in precision loss.
Solution:
Simplejson, a third-party JSON library, offers a native solution for serializing Decimal objects. Version 2.1 and higher of simplejson provide a use_decimal parameter in the dumps function. By default, use_decimal is True, allowing Decimal objects to be serialized as strings without loss of precision:
import simplejson as json decimal_object = Decimal('3.9') json_string = json.dumps(decimal_object) # Output: '3.9'
The above is the detailed content of How Can I Serialize Decimal Objects in Python JSON Without Losing Precision?. For more information, please follow other related articles on the PHP Chinese website!