Home >Backend Development >Python Tutorial >How Can I Serialize Decimal Objects to JSON in Python Without Losing Precision?
Serializing Decimal Objects to JSON in Python
When attempting to encode a Decimal object to a JSON string, users may encounter issues with JSONDecoder rejecting Decimal objects. Additionally, converting the Decimal object to a float beforehand can result in loss of precision.
Solution using Simplejson
Simplejson version 2.1 and higher provides native support for Decimal types. By default, Decimal objects are serialized as strings with the use_decimal parameter set to True. To utilize this feature:
import simplejson as json json_string = json.dumps(Decimal('3.9')) # Output: '3.9'
Anticipated Inclusion in Standard Library
This feature is expected to be incorporated into the Python standard library in the future, offering a more robust solution for serializing Decimal objects to JSON.
The above is the detailed content of How Can I Serialize Decimal Objects to JSON in Python Without Losing Precision?. For more information, please follow other related articles on the PHP Chinese website!