Encoding Decimal Objects to JSON in Python
JSON, a ubiquitous data interchange format, encounters challenges when dealing with Python's Decimal objects. To address this, we seek to serialize a Decimal('3.9') object to a JSON string that accurately represents the original value as {'x': 3.9}.
SimpleJSON to the Rescue
While Python's built-in JSON encoder cannot handle Decimals, a viable solution emerges with SimpleJSON, a third-party library. SimpleJSON version 2.1 and above boasts native support for the Decimal type. By leveraging the use_decimal parameter, we enable seamless serialization.
Here's an example:
import simplejson as json result = json.dumps(Decimal('3.9'), use_decimal=True) print(result) # Output: '3.9'
By default, use_decimal is set to True, so the following command also produces the desired result:
result = json.dumps(Decimal('3.9')) print(result) # Output: '3.9'
It is noteworthy that SimpleJSON is expected to incorporate this functionality into Python's standard library.
The above is the detailed content of How Can I Encode Python Decimal Objects to JSON Accurately?. For more information, please follow other related articles on the PHP Chinese website!