Skip to content

Allow the JSON encoder to optionally support decimal.Decimal objects #118810

Description

@chris-ashford

Feature or enhancement

Proposal:

JSON files allow real numbers of infinite size and precision.
By default, the json module parses real numbers to floats, which have limited precision.
Python already has a built-in solution for this in the form of decimal.Decimal objects.
However, while it is easy to use these with the decoder, Python's JSON encoder does not allow you to encode decimal.Decimal objects, and producing JSON with infinite precision reals requires a custom encoder at this time.
I propose that the json module have an optional flag, which when toggled allows the it to encode decimal.Decimal objects.

Example usage:

>>> import json
>>> import decimal
>>> json.dumps(decimal.Decimal("1.2345"), support_decimal=True)
'1.2345'
>>> json.dumps({decimal.Decimal("1.2345"): [decimal.Decimal("6.7890"), decimal.Decimal("3.14159265"), "some other data", decimal.Decimal("0")]}, support_decimal=True)
'{"1.2345": [6.7890, 3.14159265, "some other data", 0]}'
>>> from math import pi
>>> json.loads(json.dumps(decimal.Decimal(pi), support_decimal=True), parse_float=decimal.Decimal)
Decimal('3.141592653589793115997963468544185161590576171875')

This is my first attempt at contributing to open source, so any feedback is greatly appreciated :)

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions