0

I'm new in the scripting and web world and have been trying to work through an issue I've been having. I am reading data from a local JSON file, and have been able to use jQuery.getJSON and jQuery.parseJSON successfully, but I am trying to use the data outside of the getJSON callback function and am having issues. I think it comes down to me not fully understanding the correct way to do this, and that's where I'm looking for your help. Here's my code:

var names = new Array();

$.getJSON('ferries.json', function(data) {
  var jsondata = $.parseJSON(JSON.stringify(data));

  var length = jsondata.nodes.length;
  for (var i = 0; i < length; i++) {
    names[i] = String(jsondata.nodes[i].name);
  }
});

console.log('Names: ' + names[0]);

The final line returns undefined. If I were to write that line right after the for loop, it would return the desired value. Here's how the JSON file is structured:

{
  "nodes":[
    {
      "name":"John"
    },

    ...

    {
      "name":"Joe"
    }
  ]
}

Any help would be appreciated - thanks!

Edit: One last thing, it seems that the final line (console.log(...)) executes before the $.getJSON bit, which confuses me as well.

1
  • To get names array try this names.push(jsondata.nodes[i].name); Commented Jun 8, 2013 at 5:05

1 Answer 1

1

$.getJSON runs asynchronously. The function that you pass to it is a "callback", which means that it gets called when getJSON comes back from doing its thing.

If you want to do something with the JSON data that you get back, you must wait for the callback to execute.

Also, on a side note, $.parseJSON(JSON.stringify(data)) is redundant. The data object is already a perfectly usable object with your data in it, but you're turning that object back into a JSON string and then immediately back into an object. Just use data as is. For more information, check out the jQuery API docs for getJSON.

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

2 Comments

Thanks for the side note - that makes a lot of sense when you explain it like that. As for waiting for the callback to execute, how can I achieve that in code?
You're already waiting on getJSON to execute the callback to set the values in the names array. Whatever else you need to do, do it within the callback or call another function for the callback to do it. For more complex scenarios, read up on jQuery's Deferred object. The doc page for getJSON mentions it.

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.