RuuRuu RuuRuu - 1 year ago 148
Javascript Question

When using $.getJSON(), how do you get your JSON data from the responseText element to store into a variable?

So, as of right now, I have a database link (I'll call it "LINK"). LINK is an online JSON file. I looked online, and I found that in order to read it, you must use $.getJSON(). So, as of now, I have:

var my_data = $.getJSON(LINK);

However, this returns "Object{readyState: 1}" in the console. When I click to expand it, I find that within the object, my data is stored in something called "responseText", which appears:

Object{readyState: 1}
responseText: "{{{MY JSON DATA}}}"

Yet, when I try to print out "my_data.responseText" or "my_data.responseText()" it either returns "undefined" or " not a function". How do I get this data and convert the "my_data" variable into a JSON array?

Thanks to those who answered. Now, I am getting the data I was looking for, however, now it seems that the JQuery call runs only after all my other Javascript does. My 'url' a.k.a. LINK, is supposed to update from time to time based on user input data. Overall, I am going for something like:

var my_data;
function foo(link){
// Either my_data = response; OR
return response;
my_data = foo("random.json");
console.log(my_data); // This prints out null though

Answer Source

This is not how it works, getJSON is asyc, witch means you have to use a callback to fetch your data and pass it to a variable.

$.getJSON("url", function(response) {
    var my_data = response;

About your edited version:
This will not work too. You have to keep in mind that is asyncronous. Maybe do some research about this. But you can use a function for passing the url. You only have to do your work in the callback.

function foo(link) {
    $.getJSON(link, function(response) {
        // do your work with the json data here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download