[英]Can not parse json array
jQuery中的简单问题-但是解决方案对我来说并不明确
$( document ).ready(function() {
handleJson();
});
function handleJson(){
$.getJSON("fileList.json", function(json) {
$.each(json, function(idx, obj) {
console.log(json.fileurls[idx]);
});
});
}
这是我的json
{
"fileurls":[
"file y 2014-09-17 10_43_40",
"file x 2014-09-15 10_15_32"
]
}
控制台中的打印结果未定义
这不起作用,因为您正在调用fileurls [idx],但filurls是IDx。 idx是数组的索引,obj是其值。
在您的JSON中,数组的索引为'fileurls',其中包含两个文件名条目。
要遍历文件名,您必须遍历数组本身,因此必须在每个循环中添加第二个。 尝试这个:
function handleJson(){
$.getJSON(fileList.json, function(json) {
$.each(json, function(idx, obj) {
$.each(obj, function(idx2, obj2) {
console.log(obj2);
});
});
});
}
祝你好运博尔德
如果要明智地访问索引,则不需要进行迭代,只需这样编写:
$.getJSON("fileList.json", function(json) { console.log(json.fileurls[0]); });
您的数组是json.fileurls
, json
是单个对象,因此在json.fileurls
进行迭代:
$.each(json.fileurls, function(idx, obj) {
console.log(json.fileurls[idx]);
});
该问题可能是由于您尝试循环json对象的每个属性而不是fileurls
数组。 尝试这个:
.each(json.fileurls, function(idx, obj) {
console.log(json.fileurls[idx]);
});
尽管obj
参数实际上已经是您想要的值,所以您可以像这样使它更容易:
.each(json.fileurls, function(idx, obj) {
console.log(obj);
});
OBJ只会给您“ fileurls”,但是如果您想分别拥有“ file y 2014-09-17 10_43_40”和“ file x 2014-09-15 10_15_32”元素,则应再次遍历OBJ
$.getJSON("fileList.json", function(json) {
$.each(json, function(idx, obj) {
$.each(obj, function(count, element) {
console.log(element);
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.