Closed dmd closed 3 months ago
Hmm. It seems the JSON spec does not define nan or ±inf, but Python's json.dumps()
will permit it unless allow_nan=False
. Unfortunately, allow_nan=False
doesn't convert to None
so that it becomes null
(which is what you get from JSON.stringify(nan)
in javascript).
I guess the correct thing is something like:
import json
import math
class JSCompatEncoder(json.JSONEncoder):
def encode(self, o):
if isinstance(o, float) and math.isnan(o):
o = None
return super().encode(o)
>>> json.dumps(math.nan, cls=JSCompatEncoder)
'null'
JSON file output sometimes contains a NaN, e.g.:
I'm not sure what the right thing to do here is, but it's a little annoying because it means any JS tools to graph this data need to preprocess the file as text and then remove those NaNs instead of just parsing it as json directly.