diff --git a/Lib/json/encoder.py b/Lib/json/encoder.py index 016638549aa59b..85d8d2bb2dac00 100644 --- a/Lib/json/encoder.py +++ b/Lib/json/encoder.py @@ -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. @@ -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: @@ -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) diff --git a/Misc/NEWS.d/next/feature-112517.bpo b/Misc/NEWS.d/next/feature-112517.bpo new file mode 100644 index 00000000000000..178d4feb57a108 --- /dev/null +++ b/Misc/NEWS.d/next/feature-112517.bpo @@ -0,0 +1 @@ +The `json.encoder` module now supports overriding how NaN and Infinity values are serialized by allowing a custom `floatstr` function.