Search code examples
javascriptjqueryjsonundefinedgetjson

jQuery.getJSON always returns empty object


I've been looking for a way to include an object from a JSON file, and I've found several pages summarizing how to use $.getJSON(), and even a few answers here, but none have worked. Some have suggested I do it this way:

var json;

$.getJSON("dir/1.json", function(response){
    json = response;
});

And some have suggested it this way:

var json = $.getJSON("dir/1.json");

Neither of these work. When I try to call a property of json, such as json.title, it just gives me an error saying the variable is undefined. No one else seems to be having this problem, so what am I doing wrong?


Solution

  • Try using this:

    var json = $.getJSON( "dir/1.json" )
        .done(function( response ) {
            json = response;
            console.log( "json variable ready" );
        })
        .fail(function() {
            console.log( "error" );
        });
    

    Update

    The response object returned by $.getJSON() implements the promise interface, giving it all the properties, methods, and behavior of a promise. So json isn't ready until a response is returned or the done function is fired.