Fix - Unexpected token u in JSON at position 0 Error in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Fix - Unexpected token u in JSON at position 0 Error #

The "Unexpected token u in JSON at position 0" error occurs when we pass an undefined value 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.

unexpected token u in json at position 0

Here's an example of how the error occurs.

index.js
// ⛔️ SyntaxError: Unexpected token u in JSON at position 0 console.log(JSON.parse(undefined)); // ⛔️ SyntaxError: Unexpected token u in JSON at position 0 console.log($.parseJSON(undefined));

When an undefined value is passed to the JSON.parse method, it gets converted to a string and the first character in the string is the letter u, which is what the error message means.

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.
  2. Your server or local storage call returning an empty response.
  3. You are fetching data immediately as the page loads and causing a race condition.

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

index.js
try { const result = JSON.parse(undefined); } 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.

All JSON values must be of type string. Not all strings are valid JSON, but all JSON values have a type of string.

If you're fetching data from a server, console.log the response you're getting 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.

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

browser-console
localStorage.clear()

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

Also, when using local storage and trying to parse a JSON value, make sure you're writing a JSON value to local storage. If the value isn't already JSON, you have to pass it to the JSON.stringify method.

index.js
// 👇️ Store a JSON value in local storage localStorage.setItem('person', JSON.stringify({name: 'Tom'})); // 👇️ parse the value when accessing it const result = JSON.parse(localStorage.getItem('person'));

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)); };

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.

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.