Skip to content

Instantly share code, notes, and snippets.

@miraculixx
Created May 21, 2025 21:29
Show Gist options
  • Save miraculixx/7fc7977bb3ce015b2d48d3592764ffd4 to your computer and use it in GitHub Desktop.
Save miraculixx/7fc7977bb3ce015b2d48d3592764ffd4 to your computer and use it in GitHub Desktop.
fix cpython json encoding of nan
# this is a hack to fix https://github.com/python/cpython/issues/70293
from json import JSONEncoder
class FixedNaNJSONEncoder(JSONEncoder):
def iterencode(self, o, _one_shot=False):
# fix cpython json encoding of nan values
# see https://github.com/python/cpython/issues/98306
# this overrides JSON.enconder.iterencode by trading performance for correctness
markers = {}
_encoder = encode_basestring
_default = self.default
INFINITY = float('inf')
_inf = INFINITY
_neginf = -INFINITY
def floatstr(o, **kwargs):
if o != o:
text = 'null'
elif o == _inf:
text = 'Infinity'
elif o == _neginf:
text = '-Infinity'
else:
return repr(o)
return text
_iterencode = _make_iterencode(
markers, self.default, _encoder, self.indent, floatstr,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, _one_shot)
return _iterencode(o, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment