What the error means
JSON.parse converts its argument to a string first. undefined becomes the text undefined, and an object becomes [object Object]. Neither is JSON, so you get an error that quotes what the parser actually saw. The problem is in your code, not in the data.
The message looks like this in Chrome, Edge and Node.js (Firefox and Safari use different wording for the same problems):
"undefined" is not valid JSON
"[object Object]" is not valid JSONCommon causes
The variable is undefined
A property that does not exist, a value that was not loaded yet, or an unset environment variable passed to JSON.parse.
Broken: JSON.parse(undefined)You parse something that is already an object
Libraries such as axios and fetch's res.json() already return parsed data. Parsing it again turns the object into the text [object Object].
Broken: const { data } = await axios.get(url);
JSON.parse(data);
Valid: const { data } = await axios.get(url); // already an objectA value was stored with String() or without stringify
localStorage only stores strings. Writing an object directly stores the text [object Object]. Always use JSON.stringify when saving and JSON.parse when reading.
Broken: localStorage.setItem("user", user);
Valid: localStorage.setItem("user", JSON.stringify(user));How to find the problem
- Paste the text that you passed to JSON.parse into the editor above. The status bar shows the line and column of the first problem, and Go to error jumps there.
- Remember that the position in the message is where the parser gave up, which is often one token after the real mistake. Look at the character before it as well.
- If the text came from a request, log the raw response text before parsing it. In the browser, open the Network tab, select the request and read the Response tab.
Guard against non-string input
function safeParse(value) {
if (typeof value !== "string") return value; // already parsed (or undefined)
try {
return JSON.parse(value);
} catch {
return null;
}
}Frequently asked questions
What does JSON.parse(null) do?
It returns null, because null is converted to the text null, which is valid JSON. That is why reading a missing localStorage key does not throw.
Is undefined a JSON value?
No. JSON has null but no undefined. JSON.stringify leaves undefined properties out of objects and turns them into null inside arrays.