Home > Backend Development > Python Tutorial > How Can I Encode Python Decimal Objects to JSON Accurately?

How Can I Encode Python Decimal Objects to JSON Accurately?

Barbara Streisand
Release: 2024-12-03 10:23:10
Original
820 people have browsed it

How Can I Encode Python Decimal Objects to JSON Accurately?

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'
Copy after login

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'
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template