Unexpected token u in JSON at position 0 (but only sometimes)

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

Leave a Comment