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

DDD
Release: 2024-11-25 05:07:15
Original
382 people have browsed it

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template