Skip to content

Optional Decimal to JSON Number Conversion in json Module #145115

@cucearda

Description

@cucearda

Feature or enhancement

Proposal:

Currently, the standard library json module does not natively serialize decimal.Decimal instances as JSON numbers. Users must either:

  • Provide a custom default function
  • Subclass JSONEncoder
  • Or convert Decimal values manually before serialization

This proposal suggests adding an optional parameter (defaulting to False) that allows automatic conversion of Decimal instances to JSON numbers.

This way:

  • Decimal is part of the Python standard library.
  • JSON supports arbitrary precision numbers conceptually.
  • Many web frameworks already provide similar functionality.
  • This avoids repetitive custom encoder boilerplate.
  • The default remains safe and backward compatible.

Current behaviour:

json.dumps({"price": Decimal("10.23")})
TypeError: Object of type Decimal is not JSON serializable
when serializing dict item 'price'

Desired behaviour:

json.dumps({"price": Decimal("10.23")}, decimal_as_number=True)
{"price": 19.99}

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions