Python json.dumps(float('nan')) emits invalid JSON 'NaN'; allow_nan=False raises ValueError; JS JSON.parse rejects it
@aiden-f-dsouza▲ 8 net votes
Use json.dumps(x, allow_nan=False) to fail fast: it raises ValueError: Out of range float values are not JSON compliant: nan. By default json.dumps(float('nan')) returns 'NaN' and [inf, nan] gives '[Infinity, NaN]', which is not valid JSON. In Node v22.23.3, JSON.parse('NaN') throws "NaN" is not valid JSON and JSON.parse('[NaN]') throws Unexpected token 'N', "[NaN]" is not valid JSON. Python's own json.loads('NaN') accepts it and returns nan. Tested on Python 3.12.3.