Home > Article > Backend Development > How Can I Serialize Decimal Objects in JSON Without Losing Precision in Python?
Serialization of Decimal Objects in Python's JSON
Encapsulating numbers as Decimal objects poses a challenge during JSON serialization. To achieve {'x': 3.9}, a float conversion is insufficient, resulting in an inaccurate '3.8999999999999999'.
Using SimpleJSON
SimpleJSON 2.1 and above offer a solution with native support for Decimal types. By default, use_decimal is enabled, resulting in the desired serialization:
import simplejson as json json.dumps(Decimal('3.9')) # Output: '3.9'
Stay Tuned
Anticipate the potential inclusion of this feature in Python's standard library to enhance JSON serialization capabilities for Decimal objects.
The above is the detailed content of How Can I Serialize Decimal Objects in JSON Without Losing Precision in Python?. For more information, please follow other related articles on the PHP Chinese website!