如何检查 JSON 数据中是否存在值/属性 [英] How to check if a value/property exist in JSON data
本文介绍了如何检查 JSON 数据中是否存在值/属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 Google Books API 接收图书列表,但有时某些图书条目没有某些键/属性,例如 作者,或者没有缩略图强>.因此 JavaScript 说我试图访问的属性是未定义的,我的应用程序卡住了.
I am using Google Books API to receive a list of books, but sometimes some book entry does not have some keys/properties, e.g., Authors, or does not have a Thumbnail. Thus JavaScript says that the property im trying to access is undefined and my application stucks.
示例 包含关键工作 Java
完整链接
https://www.googleapis.com/books/v1/volumes?q=java&callback=jQuery191020691258599981666_1377508821982&_=1377508821983
例如,当作者丢失时
TypeError: row.volumeInfo.authors is undefined
我尝试了两种建议的解决方案
I tryied two solutions suggested
if ( typeof (authors) != "undefined"){}
和
if('authors' in booksObject) {}
但它们似乎都不起作用,因为即使存在此属性,它们也永远不会进入循环.
but non of them seems to work, since they never enter the loops even when this proerty exists.
这是我打电话的地方
function populateListview(books) {
//iterate each returned item
$.each(books.items, function(i, row) {
//populate each row in the list
var htmlString = '<li><a href="book_details.html?id=' + row.id + '"><img src="';
htmlString += row.volumeInfo.imageLinks.thumbnail + '"';
htmlString += 'class="ui-li-has-thumb"/><h3>';
//Check if authors exists in JSON
htmlString += row.volumeInfo.title + '</h3><p>' + row.volumeInfo.authors[0] + '</p></a></li>';
//If not add an undefined authors string in the authors
console.log(htmlString);
//append new html to the list
$('#book_list').append(htmlString);
});
$('#book_list').listview('refresh');
// refresh the list-view so new elements are added to the DOM
};
推荐答案
您可以查看 $.isArray(row.volumeInfo.authors) &&row.volumeInfo.authors.length >0
console.log(books.toString());
// iterate each returned item
$.each(books.items, function(i, row) {
// populate each row in the list
var htmlString = '<li><a href="book_details.html?id=' + row.id
+ '"><img src="';
htmlString += row.volumeInfo.imageLinks.thumbnail + '"';
htmlString += 'class="ui-li-has-thumb"/><h3>';
if ($.isArray(row.volumeInfo.authors) && row.volumeInfo.authors.length > 0) {
// code for what to do with json here
htmlString += row.volumeInfo.title + '</h3><p>'
+ row.volumeInfo.authors[0] + '</p></a></li>';
} else {
htmlString += row.volumeInfo.title + '</h3><p>' + "Author Undifined"
+ '</p></a></li>';
}
console.log(htmlString);
// append new html to the list
$('#book_list').append(htmlString);
});
$('#book_list').listview('refresh');
// refresh the list-view so new elements are added to the DOM
这篇关于如何检查 JSON 数据中是否存在值/属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文