SyntaxError: "undefined" is not valid JSON in JS [Solved]

avatar
Borislav Hadzhiev

Last updated: Mar 2, 2024
4 min

banner

# SyntaxError: "undefined" is not valid JSON in JS [Solved]

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.

syntaxerror-undefined-is-not-valid-json

You might also get the error named as:

  • "Unexpected token u in JSON at position 0 at JSON.parse"
  • or "Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"

The error message will depend on your browser or your version of Node.js.

shell
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

syntaxerror unexpected token u in json at position 0

Here's an example of how the error occurs.

index.js
// ⛔️ 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:

  1. It gets converted to a string.
  2. The JSON.parse() method attempts to parse the string.
  3. The method fails at parsing the string and throws an error.

# Common reasons the error occurs

There are multiple reasons the "Unexpected token u in JSON at position 0" error occurs when calling JSON.parse:

  1. Referencing a non-existent property on an object.
index.js
const obj = {name: 'bobby'}; // ⛔️ trying to parse an undefined property on an object JSON.parse(obj.age);

parsing an undefined object property

  1. Your server or local storage call is returning an empty response.
  2. Forgetting to convert a value to JSON before storing it in local storage.
  3. You are fetching data immediately as the page loads and causing a race condition.

# Wrap the JSON.parse call in a try/except block

To make sure you handle the error, put the JSON.parse call in a try/catch statement.

index.js
const value = undefined; try { const result = JSON.parse(value); console.log(result); } catch (err) { // 👇️ This runs console.log('Error: ', err.message); }

wrap json parse call in try except block

The code for this article is available on GitHub

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.

# All JSON values must be of type 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.

index.js
console.log(typeof undefined); // 👉️ undefined console.log(typeof {}); // 👉️ object // 👇️ string console.log(typeof JSON.stringify({name: 'bobby'}));

all json values must be of type string

The code for this article is available on GitHub

The typeof operator indicates the type of a value.

# Clear the local storage in your browser's console

If you use local storage, open your browser's console and clear the local storage as it sometimes glitches.

Press F12 to open your developer tools, click on the Console tab and enter the following command to clear your localStorage.
browser-console
localStorage.clear()

clear your local storage

Now refresh the page and see if things work as expected.

When using local storage and trying to parse a JSON value, make sure you're writing a JSON value to local storage.

# Convert the value to JSON before writing it to local storage

If the value isn't already JSON, you have to pass it to the JSON.stringify() method before writing it to local storage.

index.js
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'}
The code for this article is available on GitHub

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.

index.js
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']

# Wait for the page to load before fetching data

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().

index.js
// ✅ 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)); };
The code for this article is available on GitHub

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.

# Make sure your server sends a valid JSON response

If you're fetching data from a server, console.log the response you get and make sure it's a valid JSON string.

Does your server send a Content-Type header of application/json? Pass the value to an online JSON validator and see if you get any errors.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.