JQuery 解析 JSON 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10463131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery Parsing JSON array
提问by David Cahill
I have a JSON
output like the following:
我有JSON
如下输出:
["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.
以上似乎不起作用,没有输出任何值。
回答by kapa
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.
getJSON()
获取后还将为您解析 JSON,因此从那时起,您将使用一个简单的 Javascript 数组([]
在 JSON 中标记一个数组)。该文档还提供了有关如何处理获取的数据的示例。
You can get all the values in an array using a for
loop:
您可以使用for
循环获取数组中的所有值:
$.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).
检查您的控制台以查看输出(Chrome、Firefox/Firebug、IE)。
jQuery also provides $.each()
for iterations, so you could also do this:
jQuery 还提供$.each()
迭代,所以你也可以这样做:
$.getJSON("url_with_json_here", function(data){
$.each(data, function (index, value) {
console.log(value);
});
});
回答by Guffa
Use the parseJSON
method:
使用parseJSON
方法:
var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);
Then you have an array with the city names.
然后你有一个包含城市名称的数组。
回答by Andrej Gaspar
var dataArray = [];
var obj = jQuery.parseJSON(yourInput);
$.each(obj, function (index, value) {
dataArray.push([value["yourID"].toString(), value["yourValue"] ]);
});
this helps me a lot :-)
这对我有很大帮助:-)
回答by tailor
with parse.JSON
和 parse.JSON
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
回答by Mohammed Amine
var dataArray = [];
var obj = jQuery.parseJSON(response);
for( key in obj )
dataArray.push([key.toString(), obj [key]]);
};