NaN and Infinity in JSON
SyntaxError: Unexpected token 'N', ..." "ratio": NaN, "li"... is not valid JSON
Where it stops
{
"ratio": NaN,
"limit": InfinityWhat it means
The JSON number grammar covers an optional minus sign, digits, an optional fraction and an optional exponent. NaN, Infinity and -Infinity match none of that, and JSON has no literal for them.
Last verified on Chromium 145, Firefox 146 and WebKit 26.
It opens with the error marked. Nothing is uploaded. Find where the error is.
- Usually
- A serializer that emits the language’s own literalsA division or parse that produced NaN upstreamFloating-point overflow
- Fix
- Use
nullfor a value that has no number, and say so in your schema.
The fix
Use null for a value that has no number, and say so in your schema. If the distinction matters, encode it explicitly as a string ("NaN") and convert on read.
{
"ratio": NaN,
"limit": Infinity
}Lines 2 and 3 change.
{
"ratio": null,
"limit": null
}How the message appears
Chrome and Node first, then Firefox, then Safari.
- SyntaxError: Unexpected token 'N', ..." "ratio": NaN, "li"... is not valid JSONChrome and Node
- SyntaxError: JSON.parse: unexpected character at line 2 column 12 of the JSON dataFirefox
- SyntaxError: JSON Parse error: Unexpected identifier "NaN"Safari
- SyntaxError: Unexpected token 'N', "{"value": NaN}" is not valid JSON
- SyntaxError: JSON.parse: unexpected character at line 1 column 11 of the JSON data
What causes it
A serializer that emits the language’s own literals
Python’s
json.dumpswritesNaNandInfinityby default, which is valid Python and invalid JSON. Passallow_nan=Falseto make it raise instead of producing a document other parsers reject.A division or parse that produced NaN upstream
0/0,parseFloat("abc")and arithmetic onundefinedall yieldNaN. In JavaScript it then silently becomesnullin the output, which is usually the real bug: a missing value that reads as a deliberate one.Floating-point overflow
A number past roughly 1.8 × 10^308 becomes
Infinityin IEEE-754 double precision. Very large integers hit a related problem: past 2^53 they lose precision silently on parse.
Worth knowing
Watch outJSON.stringify also drops undefined object properties entirely and converts undefined array elements to null, so an array can change meaning without changing length.
NoteJavaScript already does this for you: JSON.stringify({a: NaN}) returns {"a":null} rather than throwing.