Home > Backend Development > Python Tutorial > How Can I Serialize Decimal Objects to JSON in Python While Preserving Precision?

How Can I Serialize Decimal Objects to JSON in Python While Preserving Precision?

Linda Hamilton
Release: 2024-12-29 18:42:12
Original
383 people have browsed it

How Can I Serialize Decimal Objects to JSON in Python While Preserving Precision?

Serializing Decimal Objects to JSON in Python

A common issue arises when attempting to encode a Decimal object into a JSON string, preserving its precision. The default approach of converting to a float results in loss of precision.

Solution 1: SimpleJSON (Python 2.1 and above)

SimpleJSON provides intuitive support for Decimal objects through its 'use_decimal' flag:

import simplejson as json

json.dumps(Decimal('3.9'), use_decimal=True)
# Output: '3.9'
Copy after login

By default, 'use_decimal' is set to True, eliminating the need for explicit specification:

json.dumps(Decimal('3.9'))
# Output: '3.9'
Copy after login

Solution 2: Custom JSON Encoder

If SimpleJSON is not an option, you can create a custom JSON encoder that handles Decimal objects:

import decimal
import json

class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            return float(obj)
        # Handle other object types as needed
        return super().default(obj)

json.dumps(Decimal('3.9'), cls=DecimalEncoder)
# Output: '3.8999999999999999'
Copy after login

Note that this approach will convert the Decimal object to a float, potentially causing precision loss.

The above is the detailed content of How Can I Serialize Decimal Objects to JSON in Python While Preserving 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template