javascript 如何使用javascript从json数组中获取值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16251566/
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
How to get values from json array using javascript?
提问by harrison4
I have a PHP file which only return an array with the drivers and a url:
我有一个 PHP 文件,它只返回一个包含驱动程序和 url 的数组:
{"drivers":[{"marco":[0],"luigi":[123],"Joan":[2444],"George":[25]}, {"marco":[23],"luigi":[3],"Joan":[244],"George":[234]}],"url":"google.es"}
Is the json correctly structured? And I'm trying to get the result using jQuery and AJAX by this way:
json 的结构是否正确?我试图通过这种方式使用 jQuery 和 AJAX 获得结果:
$.getJSON('calculate.php&someparams=123', function(data) {
alert("url - " + data.url);
var arr = data.drivers;
for (var i = 0; i < arr.length; i++) {
alert(arr[i] + " - " + arr[i][0]);
}
});
I see the first alert() with the url, but the second one does not works... What am I doing wrong?
我看到第一个带有 url 的 alert(),但第二个不起作用......我做错了什么?
If you need more info let me know and I'll edit the post.
如果您需要更多信息,请告诉我,我会编辑帖子。
回答by Arun P Johny
The drivers
is not an array, it is an object, you use $.eachto iterate through the object elements.
这drivers
不是一个数组,它是一个对象,你使用$.each来遍历对象元素。
$.getJSON('calculate.php&someparams=123', function(data) {
$.each(data.drivers, function(key, value){
$.each(value, function(key, value){
console.log(key, value);
});
})
});
回答by jeyraof
drivers
is an object. Not an array.
drivers
是一个对象。不是数组。
How about this?
这个怎么样?
var json_string = '{"drivers":{"marco":[0],"luigi":[123],"Joan":[2444],"George":[25]},"url":"google.es"}';
var obj = jQuery.parseJSON(json_string);
alert(obj.url);
回答by Quentin
That's an object, not an array. It has named properties, not numerical indexes.
那是一个对象,而不是一个数组。它具有命名属性,而不是数字索引。
You need a for in loopto loop over the properties.
您需要一个for in 循环来遍历属性。