NaN and Infinity in JSON

ErrorJavaScript

SyntaxError: Unexpected token 'N', ..." "ratio": NaN, "li"... is not valid JSON

Where it stops

{
  "ratio": NaN,
  "limit": Infinity

What 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 null for 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.

broken.jsonFails to parse
{
  "ratio": NaN,
  "limit": Infinity
}
JSON.parse stops at line 2, column 12.

Lines 2 and 3 change.

fixed.jsonParses
{
  "ratio": null,
  "limit": null
}
JSON.parse reads it.

How the message appears

Chrome and Node first, then Firefox, then Safari.

Console
  • 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

  1. A serializer that emits the language’s own literals

    Python’s json.dumps writes NaN and Infinity by default, which is valid Python and invalid JSON. Pass allow_nan=False to make it raise instead of producing a document other parsers reject.

  2. A division or parse that produced NaN upstream

    0/0, parseFloat("abc") and arithmetic on undefined all yield NaN. In JavaScript it then silently becomes null in the output, which is usually the real bug: a missing value that reads as a deliberate one.

  3. Floating-point overflow

    A number past roughly 1.8 × 10^308 becomes Infinity in 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.

What you put into the tools never leaves your browser. We count page views and keep them for 90 days. Accept and we also remember this browser, so a return visit is not counted as new. Privacy policy