1

How do I use the .getJSON() function to save a json object as a javascript variable?

var js = 
$.getJSON(url, 
    function(data) {...}
);

do I need the function(data) {...} callback?

The var would look like normal json format (like a dictionary in python?)

{"query":{"count":1,"created":"2014-07-18", ...
2
  • The function(data){...} part is the callback of getJSON, data is the JSON response that you will get. Commented Jul 18, 2014 at 5:10
  • You mean you want to receive data returned by $.getJSON in a JavaScript variable? Commented Jul 18, 2014 at 5:10

2 Answers 2

7

You would need to declare the variable first and then assign the value in the success function as such:

var js;
$.getJSON(url, 
    function(data) {
        js = data;
        // or use your data here by calling yourFunction(data);
    }
);

EDIT:

If your code looks something like the following, then it probably won't work:

var js;
$.getJSON(url, 
    function(data) {
        js = data;
        // or use your data here by calling yourFunction(data);
    }
);
$("div").html(js);

That's because the $.getJSON() is an asynchronous function. That means the code underneath will continue executing without waiting for the $.getJSON to finish. Instead you would want to use the variable inside the success function as such:

var js;
$.getJSON(url, 
    function(data) {
        // the code inside this function will be run,
        // when the $.getJSON finishes retrieving the data
        js = data;
        $("div").html(js);
    }
);
Sign up to request clarification or add additional context in comments.

3 Comments

$("div").html(js); doesnt print to my html div though?
Thanks. That is still not showing anything in the div though. I want to actually print out the json object on in my div.
before $("div").html(js); have you tried adding console.log(js); to make sure the $.getJSON is retrieving the data correctly? If not, let me know what it prints
0

Assuming you want to receive data returned by $.getJSON in a javascript variable.

var js;

$.getJSON(url, function(data) {
    js = data;
    // you can even pass data as parameter to your target function like myFunct(data);
});

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.