Reading a JSON and looping on it

I have a JSON array of strings stored in a file, I want to read it from a JavaScript and use in someway its values. To simplify the file access, I am about to use the jQuery getJSON() function.

The JSON file, named numbers.json, contains something like this:
["Zero", "One", "Two", "Three"]

This JavaScript fragment gets asynchronously the file, and then dumps to the console any elements in the fetched JSON:
$.getJSON('numbers.json').done(function(numbers) {
  for(var i=0; i < numbers.length; ++i) {
    console.log(numbers[i]);
  }
});
Calling getJSON() we ask jQuery to fetch the content of the passed filename and, when done, calling the anonymous function passed as parameter to done(), putting in its input parameter, that I named numbers, the contained JSON. In the body of that anonymous function we have to deal with the fetched data. What I do there is simply looping on the array, and logging to the console each component.

No comments:

Post a Comment