Loading...
Loading...
SyntaxError: Unexpected token 'u', "undefined" is not valid JSONThis error occurs when you call JSON.parse() on the string 'undefined' or on an actual JavaScript undefined value. JavaScript converts undefined to the string 'undefined' in some contexts, which is not valid JSON.
Always check that the value exists and is a string before calling JSON.parse().
const raw = localStorage.getItem('myKey');
if (raw) {
const data = JSON.parse(raw);
}Use the nullish coalescing operator to fall back to a safe default.
const data = JSON.parse(raw ?? '{}');Paste your JSON into our formatter to instantly see if it is valid and where the error is.
In JavaScript, undefined is a primitive type, not a valid value in the JSON specification. When you pass undefined to JSON.parse(), the engine first coerces it to the string "undefined". Since the JSON parser expects the first character to be {, [, ", true, false, null, or a digit, it encounters the u in "undefined" and throws this error.
This is most common with localStorage.getItem(). If a key doesn't exist, it returns null. If your code coincidentally results in an undefined being stored (e.g., localStorage.setItem('x', someUndefinedVar)), the browser stores the literal string "undefined". Parsing this back will always fail.