尝试在复杂的嵌套JSON数组中检索特定值是非常棘手的。我认为这是另一种方式来做到这一点,而不是我在下面:
$.getJSON('test.json', function (data) {
$.each(data.glossary, function (){
$('ul#results').append('<li><div class=\"name\">' +this.title+ '</div></li><li><div class=\"name\">' +this.GlossTerm+ '</div></li>');
});
});
test.json是:
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "Hello!!",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
到目前为止,在网页上,返回的结果是:
+未定义
+未定义
+你好!
+未定义
如何使未定义的值显示正确的值?我尝试了很多方法,似乎都没有用!
答案 0 :(得分:2)
你需要正确地遍历对象,没办法吗?
$.getJSON('test.json', function (data) {
$.each(data.glossary, function(index, val){
var title = val.title, //"example glossary"
term = val.GlossDiv.GlossList.GlossEntry.GlossTerm; //"Standard Generalized Markup Language"
});
});