You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Allow the JSON encoder to optionally support decimal.Decimal objects #118810
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:
>>>importjson>>>importdecimal>>>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]}'>>>frommathimportpi>>>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
Sorry for not finding that before.
In case anyone stumbles upon this issue in the future, I've made the code from this PR into its own module, and uploaded it to PyPI. It can function as a drop-in replacement for json (support_decimal is true by default in this version):
importjson_with_decimalsasjsonfromdecimalimportDecimal# In this version, real numbers are automatically made into Decimalsjson.loads(json.dumps(Decimal("1.2345")))
# Returns the same Decimal you passed in
Activity
serhiy-storchaka commentedon May 10, 2024
It is a duplicate of #60739.
kris-the-meowvellous commentedon May 12, 2024
Sorry for not finding that before.
In case anyone stumbles upon this issue in the future, I've made the code from this PR into its own module, and uploaded it to PyPI. It can function as a drop-in replacement for
json(support_decimalis true by default in this version):