Skip to content

gh-134717: Allow overriding serialization of NaN and Infinity in json.encoder #134715

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
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 23 additions & 24 deletions Lib/json/encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,28 @@ def encode(self, o):
chunks = list(chunks)
return ''.join(chunks)

def floatstr(o, allow_nan=self.allow_nan,
_repr=float.__repr__, _inf=INFINITY, _neginf=-INFINITY):
# Check for specials. Note that this type of test is processor
# and/or platform-specific, so do tests which don't depend on the
# internals.

if o != o:
text = 'NaN'
elif o == _inf:
text = 'Infinity'
elif o == _neginf:
text = '-Infinity'
else:
return _repr(o)

if not allow_nan:
raise ValueError(
"Out of range float values are not JSON compliant: " +
repr(o))

return text

def iterencode(self, o, _one_shot=False):
"""Encode the given object and yield each string
representation as available.
Expand All @@ -221,29 +243,6 @@ def iterencode(self, o, _one_shot=False):
else:
_encoder = encode_basestring

def floatstr(o, allow_nan=self.allow_nan,
_repr=float.__repr__, _inf=INFINITY, _neginf=-INFINITY):
# Check for specials. Note that this type of test is processor
# and/or platform-specific, so do tests which don't depend on the
# internals.

if o != o:
text = 'NaN'
elif o == _inf:
text = 'Infinity'
elif o == _neginf:
text = '-Infinity'
else:
return _repr(o)

if not allow_nan:
raise ValueError(
"Out of range float values are not JSON compliant: " +
repr(o))

return text


if self.indent is None or isinstance(self.indent, str):
indent = self.indent
else:
Expand All @@ -255,7 +254,7 @@ def floatstr(o, allow_nan=self.allow_nan,
self.skipkeys, self.allow_nan)
else:
_iterencode = _make_iterencode(
markers, self.default, _encoder, indent, floatstr,
markers, self.default, _encoder, indent, self.floatstr,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, _one_shot)
return _iterencode(o, 0)
Expand Down
1 change: 1 addition & 0 deletions Misc/NEWS.d/next/feature-112517.bpo
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The `json.encoder` module now supports overriding how NaN and Infinity values are serialized by allowing a custom `floatstr` function.
Loading