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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18440522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:56:10  来源:igfitidea点击:

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

javascriptjqueryjsonapidom

提问by Lali Pali

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.

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

Example Json data example from a book search containing the keywork Java

来自包含关键字 Java 的书籍搜索的示例Json 数据示例

Full link

完整链接

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

E.g., when Authorsis missing

例如,当Authors丢失时

TypeError: row.volumeInfo.authors is undefined

I tryied two solutions suggested

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

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

and

if('authors' in booksObject) {}

but non of them seems to work, since they never enter the loops even when this proerty exists.

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

This is where I call

这是我打电话的地方

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
};

采纳答案by Arun P Johny

You can check $.isArray(row.volumeInfo.authors) && row.volumeInfo.authors.length > 0

你可以检查 $.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

回答by Sushrut

Try this :

试试这个 :

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

回答by e.w. parris

Here's a really simple way to check if any key or value exists in your JSON.

这是一种非常简单的方法来检查您的 JSON 中是否存在任何键或值。

var jsonString = JSON.stringify(yourJSON);

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

It's quick, simple, easy.

它快速、简单、容易。