Serializing Decimal Objects to JSON in Python
A common issue arises when attempting to encode a Decimal object into a JSON string, preserving its precision. The default approach of converting to a float results in loss of precision.
Solution 1: SimpleJSON (Python 2.1 and above)
SimpleJSON provides intuitive support for Decimal objects through its 'use_decimal' flag:
import simplejson as json json.dumps(Decimal('3.9'), use_decimal=True) # Output: '3.9'
By default, 'use_decimal' is set to True, eliminating the need for explicit specification:
json.dumps(Decimal('3.9')) # Output: '3.9'
Solution 2: Custom JSON Encoder
If SimpleJSON is not an option, you can create a custom JSON encoder that handles Decimal objects:
import decimal import json class DecimalEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, decimal.Decimal): return float(obj) # Handle other object types as needed return super().default(obj) json.dumps(Decimal('3.9'), cls=DecimalEncoder) # Output: '3.8999999999999999'
Note that this approach will convert the Decimal object to a float, potentially causing precision loss.
The above is the detailed content of How Can I Serialize Decimal Objects to JSON in Python While Preserving Precision?. For more information, please follow other related articles on the PHP Chinese website!