fjordtools / Errors / Unexpected token u in JSON

Unexpected token u in JSON at position 0

The text you parsed starts with the letter u: it is the word undefined. JSON.parse turns its argument into a string first, so passing the undefined value, for example a missing localStorage key or an empty property, parses the text undefined, which is not JSON. Find where the value is lost.

Fjordtools team · Seen in Chrome and Node (V8) · Published · 1 min read

How browsers word it

Chrome and Node (V8), newer"undefined" is not valid JSON
Chrome and Node, olderUnexpected token u in JSON at position 0
FirefoxJSON.parse: unexpected character at line 1 column 1 of the JSON data
SafariJSON Parse error: Unrecognized token 'u'

Common causes

  1. The value was undefined

    A variable that was never set, a missing property or a function without a return value gives undefined. JSON.parse converts it to the text undefined.

    Input

    undefined

    JSON Formatter says

    "undefined" is not valid JSON
  2. An object was turned into text the wrong way

    Joining an object into a string gives [object Object], not JSON. Use JSON.stringify to write it and JSON.parse to read it back.

    Input

    [object Object]

    JSON Formatter says

    Unexpected word "object". Strings need double quotes; the only bare words are true, false and null
  3. A JavaScript value that JSON does not have

    NaN, Infinity and undefined exist in JavaScript but not in JSON. The only bare words JSON allows are true, false and null.

    Input

    NaN

    JSON Formatter says

    "NaN" is not valid JSON

How to fix it

  1. Log the exact value you pass to JSON.parse, and its type.
  2. For localStorage.getItem, check for null before parsing, and write values with JSON.stringify.
  3. Give the parse a fallback: parse only when the value is a non-empty string.
  4. Paste the text into the JSON formatter to see what is wrong with it.

Related errors

More error explainers are coming

See all errors.