簡體   English   中英

如何檢查JSON數據中是否存在值/屬性

[英]How to check if a value/property exist in JSON data

我使用Google Books API接收圖書清單,但有時一些圖書條目沒有某些鍵/屬性,例如作者 ,或者沒有縮略圖 因此JavaScript說我試圖訪問的屬性是未定義的,我的應用程序卡住了。

示例Json數據示例來自包含關鍵字Java的書籍搜索

完整鏈接

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

例如,當作者遺失時

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

嘗試這個 :

if(booksObject.image) {
 //do stuff with it
 } else if( booksObject.author ) {
 //do stuff with author
 }

這是檢查JSON中是否存在任何鍵或值的一種非常簡單的方法。

var jsonString = JSON.stringify(yourJSON);

if (jsonString .indexOf("yourKeyOrValue") > -1){
    console.log("your key or value exists!");
}

它快速,簡單,容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM