JQuery Parsing JSON array
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.
Solution 1:
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);
});
});
Solution 2:
Use the parseJSON
method:
var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);
Then you have an array with the city names.
Solution 3:
var dataArray = [];
var obj = jQuery.parseJSON(yourInput);
$.each(obj, function (index, value) {
dataArray.push([value["yourID"].toString(), value["yourValue"] ]);
});
this helps me a lot :-)