0

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?

2
  • Do you understand the difference between a relative path and an absolute path? Commented Jan 17, 2016 at 5:48
  • Yes, and the file is relative to that. Commented Jan 17, 2016 at 6:15

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Just did it. Thanks for the suggestion
1

The response is deferred. At the time you're reading the variable, the response likely hasn't responded yet. Try accessing the variable inside the function callback, right after json = response;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.