close

[Solved] Uncaught SyntaxError: Unexpected token u in JSON at position 0

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Uncaught SyntaxError: Unexpected token u in JSON at position 0 in javascript. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Uncaught SyntaxError: Unexpected token u in JSON at position 0 Error Occurs?

Today I get the following error.

Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at window.onload (profile.js:8)

Here is my code.

var jqxhr = $.getJSON( "main.json", function(data) {
    return data;
});

var json;
window.onload = function() {
    var jsonTxt = jqxhr.responseText;
    json = JSON.parse(jsonTxt);
    ....
}

How To Solve Uncaught SyntaxError: Unexpected token u in JSON at position 0 Error?

  1. How To Solve Uncaught SyntaxError: Unexpected token u in JSON at position 0 Error?

    To Solve Uncaught SyntaxError: Unexpected token u in JSON at position 0 Error A solution is to move the JSON loading inside the onload even handler. Additionally, the whole point of getJSON is that it already parses the response for you as a JSON object, so there is no need for JSON.parse()

  2. Uncaught SyntaxError: Unexpected token u in JSON at position 0

    To Solve Uncaught SyntaxError: Unexpected token u in JSON at position 0 Error A solution is to move the JSON loading inside the onload even handler. Additionally, the whole point of getJSON is that it already parses the response for you as a JSON object, so there is no need for JSON.parse()

Solution 1

That unexpected “u” is the first letter of the string “undefined”. 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.

A solution is to move the JSON loading inside the onload even handler. Additionally, the whole point of getJSON is that it already parses the response for you as a JSON object, so there is no need for JSON.parse():

window.onload = function() {
    $.getJSON( "main.json", function(json) {
        // process the results here
    });
}

Solution 2

Insert a try catch block where the JSON.parse() is called.

It is possible that the text itself is not JSON.

For example…

I think this is the issue because if response text is undefined, the char ‘u’ is at position 0. So JSON.parse() is working with a string. Not a javascript-object-notation text file.

if(response !== undefined){
    try{
    // do parse
    }
    catch(errror){
        console.error("Not a JSON response")
    }
}

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read

Leave a Comment