javascript - 如何检查 JSON 数据中是否存在值/属性

标签 javascript jquery json api dom

我正在使用 Google Books API 接收图书列表,但有时某些图书条目没有某些键/属性,例如,作者,或者没有缩略图。因此 JavaScript 说我试图访问的属性是未定义的,我的应用程序卡住了。

示例 Json data example from a book search containing the keywork Java

完整链接

https://www.googleapis.com/books/v1/volumes?q=java&callback=jQuery191020691258599981666_1377508821982&_=1377508821983

例如,当 Authors 缺失时

TypeError: row.volumeInfo.authors is undefined

我尝试了两个建议的解决方案

if ( typeof (authors) != "undefined"){}

if('authors' in booksObject) {}

但它们似乎都不起作用,因为即使存在此属性,它们也不会进入循环。

这是我打电话的地方

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

关于javascript - 如何检查 JSON 数据中是否存在值/属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18440522/

相关文章:

javascript - Fancybox - 当到达最后一张图片时滑动到另外五张

javascript - VueJS 响应式日期对象

javascript - NPM 注册表中缺少 @types/eslint v8.4.4

javascript - 无法从 Facebook 检索事件对象?

javascript - 在下面的例子中, "<ul/>"是拼写错误还是有特殊含义?

python - 解析字典的最快 pythonic 方式,其中值是字节字符串化的 json 对象

php - IE :"This.container"为 null 或不是对象

javascript - 无法让我的 post() 使用 jQuery Ajax 工作

json - golang 将接口(interface)数组转换为字符串

c# - 使用 Newtonsoft Json 从流中反序列化多个 json 对象