"undefined" is not valid JSON
SyntaxError: "undefined" is not valid JSON
Where it stops
undefinedWhat 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;
undefinedLine 1: change undefined to null.
nullHow the message appears
Chrome and Node first, then Firefox, then Safari. Older versions of Chrome and Node word it differently. Those lines are marked.
- 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
localStorage
By far the most common source.
localStorage.setItem("k", undefined)stores the six-character string"undefined", andJSON.parse(localStorage.getItem("k"))then throws. A missing key is different.getItemreturnsnull, andJSON.parse(null)returnsnullwithout throwing, so that bug shows up somewhere else.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.JSON.stringify of undefined
JSON.stringify(undefined)returnsundefined: 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.