Skip to content

Allow customization of NaN and Infinity serialization in json module #134717

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
krzyszti opened this issue May 26, 2025 · 2 comments
Open

Allow customization of NaN and Infinity serialization in json module #134717

krzyszti opened this issue May 26, 2025 · 2 comments
Labels
stdlib Python modules in the Lib dir type-feature A feature request or enhancement

Comments

@krzyszti
Copy link

krzyszti commented May 26, 2025

Feature or enhancement

Proposal:

Body:
The json module currently serializes special floating-point values such as NaN, Infinity, and -Infinity as unquoted identifiers when allow_nan=True, which is non-standard JSON. While this behavior is useful in some contexts, there is currently no built-in way to override how these values are serialized when using json.dumps() or json.encoder.JSONEncoder.

Use Case:
Some applications may need to emit null, a fixed numeric value (like 0), or a quoted string (e.g., "NaN") instead of the default NaN, Infinity, and -Infinity. This is particularly important when interoperating with systems expecting strict or customized JSON.

Proposal:
Introduce a way to override the serialization of these special float values via a floatstr parameter, enabling developers to supply a callable that determines how to stringify such values.

Code of floatstr will not change, but it would be moved to the class, therefore it would allow the function to be overriten with custom value for NaN, infinite and -infinite.

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

@nineteendo
Copy link
Contributor

@picnixz, could you add this to JSON issues?

@picnixz picnixz added the stdlib Python modules in the Lib dir label May 27, 2025
@nineteendo
Copy link
Contributor

Wouldn't a hook be more flexible?

import jsonyx as json
from math import inf, isfinite, nan

def float_hook(obj):
    if isinstance(obj, float) and not isfinite(obj):
        return None
    return obj

json.dump([nan, inf, -inf], hook=float_hook) # [null, null, null]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stdlib Python modules in the Lib dir type-feature A feature request or enhancement
Projects
Status: No status
Development

No branches or pull requests

3 participants