Last updated: Mar 2, 2024
Reading time·4 min
The "SyntaxError: "undefined" is not valid JSON" error occurs when we pass a
value that is not valid JSON to the JSON.parse
or $.parseJSON
methods.
To solve the error, inspect the value you're trying to parse and make sure it's a valid JSON string before parsing it.
You might also get the error named as:
The error message will depend on your browser or your version of Node.js.
SyntaxError: "undefined" is not valid JSON Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse(<anonymous>) at index.js:3 Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Here's an example of how the error occurs.
// ⛔️ Uncaught SyntaxError: "undefined" is not valid JSON // Unexpected token u in JSON at position 0 at JSON.parse console.log(JSON.parse(undefined)); // ⛔️ Uncaught SyntaxError: "undefined" is not valid JSON // Unexpected token u in JSON at position 0 at JSON.parse console.log($.parseJSON(undefined));
When an undefined
value is passed to the
JSON.parse method:
There are multiple reasons the "Unexpected token u in JSON at position 0" error
occurs when calling JSON.parse
:
const obj = {name: 'bobby'}; // ⛔️ trying to parse an undefined property on an object JSON.parse(obj.age);
To make sure you handle the error, put the JSON.parse
call in a try/catch
statement.
const value = undefined; try { const result = JSON.parse(value); console.log(result); } catch (err) { // 👇️ This runs console.log('Error: ', err.message); }
The try
block tries to parse the value and assigns it to a variable.
However, if the passed-in value is not a valid JSON string, the error gets
caught and handled in the catch
block.
string
All JSON values must be of type string
. Not all strings are valid JSON, but
all JSON values have a type of string
.
You can use the typeof
operator to check the type of a value.
console.log(typeof undefined); // 👉️ undefined console.log(typeof {}); // 👉️ object // 👇️ string console.log(typeof JSON.stringify({name: 'bobby'}));
The typeof
operator indicates the type of a value.
If you use local storage, open your browser's console and clear the local storage as it sometimes glitches.
F12
to open your developer tools, click on the Console
tab and enter the following command to clear your localStorage
.localStorage.clear()
Now refresh the page and see if things work as expected.
If the value isn't already JSON, you have to pass it to the JSON.stringify()
method before writing it to local storage.
const obj = {name: 'Tom'} // 👇️ Store a JSON value in local storage localStorage.setItem('person', JSON.stringify(obj)); // 👇️ parse the value when accessing it const result = JSON.parse(localStorage.getItem('person')); console.log(result); // 👉️ {name: 'Tom'}
We convert the object to a JSON string and store the JSON string as a key on the
localStorage
object.
You have to do the same when working with arrays.
const arr = ['bobby', 'hadz', 'com']; // 👇️ Store a JSON value in local storage localStorage.setItem('site', JSON.stringify(arr)); // 👇️ parse the value when accessing it const result = JSON.parse(localStorage.getItem('site')); console.log(result); // 👉️ ['bobby', 'hadz', 'com']
If you're reading data from a file or fetching data on the server immediately as
the page loads, use window.onload
or $(document).ready()
.
// ✅ using jQuery $(document).ready(function () { $.getJSON('https://randomuser.me/api/', function (data) { console.log(data); }); }); // ✅ using fetch window.onload = function getUser() { fetch('https://randomuser.me/api/') .then(response => { if (!response.ok) { throw new Error(`Error status: ${response.status}`); } return response.json(); }) .then(result => { console.log(result); }) .catch(err => console.log(err)); };
We make a request to the server after the DOM or window has loaded. This helps us avoid any race conditions like trying to parse a value before the DOM is fully loaded.
If you're fetching data from a server, console.log
the response you get and
make sure it's a valid JSON string.
Content-Type
header of application/json
? Pass the value to an online JSON validator and see if you get any errors.