Unexpected token u in JSON at position 0

Total
0
Shares

The Unexpected token u in JSON at position 0 mainly occurs if we pass an undefined value to JSON.parse() method or $.parseJSON() method.

We can resolve the error by ensuring that the object we pass to JSON.parse() is a valid JSON string.

What is SyntaxError: Unexpected token u in JSON at position 0?

Let us take a simple example to reproduce this issue in your terminal or console.

JSON.parse(undefined)

Below would be the output when you run the above code

SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)

The JSON.parse() method attempts to parse undefined as JSON; since the parsing fails, it will throw a SyntaxError.

Here the undefined gets converted to a string, and the string’s first character starts with the letter ‘u’ and is in the position 0. Hence the error message outputs as Unexpected token u in JSON at position 0

There are multiple other reasons for the Unexpected token u in JSON at position 0 error when we call JSON.parse()

  • If we try to access a property that does not exist in the JSON.
  • If we are fetching the data from an external source, it may return empty or undefined
  • If the response returned by the API is not a valid JSON, For Ex – attempting to parse an Object.
  • Race Condition – It happens because your two asynchronous operations (i.e. loading the JSON and loading the window) are racing to completion, and if the JSON isn’t loaded fast enough, the window.onload method will attempt to parse the JSON string that isn’t loaded yet.

Fix – SyntaxError: Unexpected token u in JSON at position 0

Based on the issues stated above, there are different solutions for each root cause. 

Solution – Handling undefined with a condition.

For some reason, if your service or API returns a response as undefined, we can add a condition before parsing the JSON, as shown below.

const foobar = undefined

if (foobar != undefined) {
    console.log(JSON.parse(foobar))
}

else {
    console.log("Not a valid data to parse")
}

Output

Not a valid data to parse

Solution – Handling invalid response

The better way to handle the error is by wrapping the JSON.parse() method inside a try-catch block and also checking if the data is not undefined.

It will also ensure that the response returned from the API is of a different format, such as Plain text, HTML, XML, etc.

// Plain Text
const foobar = "Hello World"

if (foobar != undefined) {
    try {
        console.log(JSON.parse(foobar))
    } catch (error) {
        console.log("Error Parsing JSON")
    }

}

Output

Error Parsing JSON

Solution – In case of the object and invalid property access

In other situations, we receive an object as a response and try to parse that object into JSON, which will lead to an Error.

We can resolve the error by first stringifying the JSON object and then parsing it into a JSON; otherwise, use the object directly in your code if you do not want to deep copy the object.

Note: The JSON.parse() method accepts the JSON string as an input and converts it into a Javascript object as output.

const foobar = {
    name: "Microsoft",
    sector: "Development",
    address: {
        state: "Karnataka",
        city: "Bangalore",
        country: "India"
    }
}

// Stringify the object first before calling JSON.parse()
str_format = JSON.stringify(foobar)
console.log(JSON.parse(str_format))

Output

{
  name: 'Microsoft',
  sector: 'Development',
  address: { state: 'Karnataka', city: 'Bangalore', country: 'India' }
}

The other common mistake developers may make accessing an invalid property name that does not exist or misspelling the property name in the code, which can lead to a SyntaxError.

In our below example, we do not have a property with “add”, so stringifying the invalid property returns undefined, and if we pass undefined to JSON.parse() will lead to a SyntaxError.

const foobar = {
    name: "Microsoft",
    sector: "Development",
    address: {
        state: "Karnataka",
        city: "Bangalore",
        country: "India"
    }
}

str_format = JSON.stringify(foobar.add)
console.log(JSON.parse(str_format))

Output


SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)

Solution – In case of Race Condition

In the Case of the Race condition two asynchronous operations (i.e. loading the JSON and loading the window) are racing to completion, and if the JSON isn’t loaded fast enough, the window.onload method will attempt to parse the JSON string that isn’t loaded yet.

// jQuery
window.onload = function() {
    $.getJSON( "https://jsonplaceholder.typicode.com/todos/1", function(json) {
        // process the results here
    });
}

// JavaScript Fetch
window.onload = function getUser() {
  fetch('https://jsonplaceholder.typicode.com/todos/1')
    .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));
};

Conclusion

The Unexpected token u in JSON at position 0 mainly occurs if we pass an undefined value to JSON.parse() method or $.parseJSON() method or if the data is not valid JSON string format.

We can fix the error by ensuring the data is a valid JSON string before parsing it using the JSON.parse() method. We can also wrap the entire code inside the try-catch block and handle other unforeseen errors like parsing Plain text, XML, HTML, JavaScript objects, Invalid Properties, etc.

Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified on the latest articles

You May Also Like