JQuery Parsing JSON array

David Cahill picture David Cahill · May 5, 2012 · Viewed 233.4k times · Source

I have a JSON output like the following:

["City1","City2","City3"]

I want to get each of the city names, how can i do this?

$.getJSON("url_with_json_here",function(json){

});

EDIT:

$.getJSON('url_here', function(data){
    $.each(data, function (index, value) {
      $('#results').append('<p>'+value+'</p>');
        console.log(value);
    });
});

The above doesn't seem to be working, no values are outputted.

Answer

kapa picture kapa · May 5, 2012

getJSON() will also parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON). The documentation also has examples on how to handle the fetched data.

You can get all the values in an array using a for loop:

$.getJSON("url_with_json_here", function(data){
    for (var i = 0, len = data.length; i < len; i++) {
        console.log(data[i]);
    }
});

Check your console to see the output (Chrome, Firefox/Firebug, IE).

jQuery also provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (index, value) {
        console.log(value);
    });
});