How to fix: Unexpected token u in JSON at position 0 Error in JS

2 Solutions for Unexpected token “u” in JSON at position 0

The [Unexpected token u in JSON at position 0] error message happens when you see an undefined value to $.parseJSON or JSON.parse functions. To fix the problem, check the value you’re attempting to convert and ensure that the JSON is valid before converting it.

Let’s one example of how to reproduce the error, so you can understand how to fix it:

Uncaught SyntaxError: Unexpected                  VM1251:1
token u in JSON at position 0
      at JSON. parse (<anonymous>)
      at index.js:3

Debugging

Let’s see one example of how to reproduce the error, so you can understand how to fix it:

Here’s an example of how the error occurs.

SyntaxError: Unexpected token u in JSON at position 0
console.log(JSON.parse(undefined));

Also:

SyntaxError: Unexpected token u in JSON at position 0
console.log($.parseJSON(undefined));

When you pass an undefined to the JSON.parse function, the value will be converted to a String.

The String here is the “u”. What contains on “u” variable? It’s only the error message.

Inside the “u”, we have the error message: “Unexpected token u in JSON at position 0″.

Root Cause

Unexpected token u in JSON at position 0

But what “Unexpected token u in JSON at position 0″ means? And why this error happened?

Let’s summarize 3 reasons why the function JSON.parse failed:

First

A non-existent attribute of an object was referenced.

Second

An empty response from your local storage or even for your server was empty.

Third

A race condition could happen if you pull the data too early before the page loads.

A better approach and best practice, it’s recommended to use JSON.parse within a try-and-catch.

What does the Try do?


try {
  const obj = JSON.parse(undefined); # Try to convert and assign
} catch (e) {
  // The line below run only if an error happened.
  console.log('Message: ', e.message);
}

The code above calls the JSON.parse from inside the try. So, attempt to convert the value and put the value inside the variable obj. But, in case of the value is invalid (an invalid JSON), the function (JSON.parse) will raise a new exception so that the catch block will handle the error.

One thing is worth highlighting. All JSON values are strings, but remember that JSON has your unique “roles” and syntax, so it means that the string should contain those roles to be valid.

Also, before pulling data from your backend, make sure that the response is a valid string. You can take advantage of the console.log to print out the response and check if the JSON is valid.

Also, always check on Developer Tools from Google Chrome, for example, if your request to the server contains the application/json in the header “Content-Type”.

Tip: You can easily find a website where you can copy and paste your JSON and check if it’s valid. It’s useful for a big string where you can’t catch small issues.

Also, try to clean all browser data and try again if possible. I like to use the Guest mode or Incognito from Google Chrome to ensure it is not a cache issue.

For example, to clean all local storage, you can execute the following method above:

localStorage.clear()

After cleaning the Local Storage, it’s important to make sure that you write the value again to the Local Storage. If the value is not JSON, you can convert it using JSON.stringify.


// Let's store a JSON value in local storage 
localStorage.setItem('site', JSON.stringify({blog: 'BitsLovers'}));

// Now let's try to parse it
const obj = JSON.parse(localStorage.getItem('site'));

Also, there is one specific scenario where you may read data from a file without waiting enough time to fully load the page.

On complex scenarios where you need to wait for the page to load, you can take advantage of the window.onload function. Alternatively, you can also use the $(document).ready(), which uses Jquery.

Let’s see how you can easily do it.


// using onload
window.onload = function getUser() {
  fetch('https://app.bitslovers.com/api/')
    .then(response => {
      if (!response.ok) 
        throw new Error(`Error message: ${response.status}`);
      return response.json();
    })
    .then(result => {console.log(result);})
    .catch(err => console.log(err));
};

// using ready from jQuery
$(document).ready(function () {
  $.getJSON('https://aps.bitslovers.com/api/', function (resp) {
    console.log(resp);
  });
});

Conclusion

You can perform some requests to your server to pull data after all elements within DOM or window are fully loaded, easily by using a simple method provided by Jquery or the onload, and also will avoid race conditions.

The problem “Unexpected token u in JSON at position 0” always happens if you pass an undefined to the function JSON.parse or $.parseJSON. The easy solution checks the value received before parsing to ensure that the JSON is valid.

Extra tip: Use Maven to compile your Java and Javascript projects.

Leave a Comment

Your email address will not be published. Required fields are marked *

Download

Free PDF with a useful Mind Map that illustrates everything you should know about AWS VPC in a single view.

Exit mobile version