Home >Backend Development >Python Tutorial >How Can I Serialize Decimal Objects in Python JSON Without Losing Precision?

How Can I Serialize Decimal Objects in Python JSON Without Losing Precision?

DDD
DDDOriginal
2024-11-25 05:07:15401browse

How Can I Serialize Decimal Objects in Python JSON Without Losing Precision?

Serialization of Decimal Objects in Python JSON

Serializing Decimal objects to JSON presents a challenge due to the lack of support for Decimal objects in JSONDecoder. Converting Decimal objects to floats can result in precision loss.

Solution:

Simplejson, a third-party JSON library, offers a native solution for serializing Decimal objects. Version 2.1 and higher of simplejson provide a use_decimal parameter in the dumps function. By default, use_decimal is True, allowing Decimal objects to be serialized as strings without loss of precision:

import simplejson as json

decimal_object = Decimal('3.9')
json_string = json.dumps(decimal_object)
# Output: '3.9'

The above is the detailed content of How Can I Serialize Decimal Objects in Python JSON Without Losing Precision?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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