JQuery Parsing JSON array

拟墨画扇 提交于 2019-11-27 00:14:27

问题


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.


回答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);
    });
});



回答2:


Use the parseJSON method:

var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);

Then you have an array with the city names.




回答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 :-)




回答4:


var dataArray = [];
var obj = jQuery.parseJSON(response);
  for( key in obj ) 
  dataArray.push([key.toString(), obj [key]]);
};



回答5:


with parse.JSON

var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );


来源:https://stackoverflow.com/questions/10463131/jquery-parsing-json-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!