"undefined" is not valid JSON

ErrorJavaScript

SyntaxError: "undefined" is not valid JSON

Where it stops

undefined

What it means

Something converted the value undefined to the six-character string "undefined" and handed that to JSON.parse. JSON has no undefined literal: the absent value in JSON is null.

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
localStorageA function with no return valueJSON.stringify of undefined
Fix
Fix the writer, not the reader.

The fix

Fix the writer, not the reader. Store null for an absent value, and guard the read: const raw = localStorage.getItem("k"); const value = raw && raw !== "undefined" ? JSON.parse(raw) : null;

broken.jsonFails to parse
undefined
JSON.parse stops at line 1, column 1.

Line 1: change undefined to null.

fixed.jsonParses
null
JSON.parse reads it.

How the message appears

Chrome and Node first, then Firefox, then Safari. Older versions of Chrome and Node word it differently. Those lines are marked.

Console
  • SyntaxError: "undefined" is not valid JSONChrome and Node
  • SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON dataFirefox
  • SyntaxError: JSON Parse error: Unexpected identifier "undefined"Safari
  • SyntaxError: Unexpected token u in JSON at position 0Older V8 wording

What causes it

  1. localStorage

    By far the most common source. localStorage.setItem("k", undefined) stores the six-character string "undefined", and JSON.parse(localStorage.getItem("k")) then throws. A missing key is different. getItem returns null, and JSON.parse(null) returns null without throwing, so that bug shows up somewhere else.

  2. A function with no return value

    A code path that falls off the end returns undefined. Interpolated into a template literal it becomes "undefined" and travels onward as text.

  3. JSON.stringify of undefined

    JSON.stringify(undefined) returns undefined: the value, not a string. Write that to a file or a cache and the next reader gets "undefined" back.

Worth knowing

NoteThe older Unexpected token u in JSON at position 0 says the same thing: u is the first character of undefined.

NoteJSON.parse(undefined) coerces its argument to the string "undefined" first, so passing the value and passing the string fail identically.

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