Javascript 如何使用jquery检查JSON返回是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14345761/
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-08-24 16:28:06  来源:igfitidea点击:

How to check if JSON return is empty with jquery

javascriptjqueryajaxjson

提问by BaconJuice

$.getJSON(url, function(json) {
  var output = '';
  $.each(json, function(i,d) {

    if(d.DESCRIPTION == 'null'){ 
      console.log("Its empty");
    }
    var description = d.DESCRIPTION;
    output += '<tr><td>'+d.NAME+'</td><td>'+'<tr><td>'+d.DESCRIPTION+'</td><td>';
  });
});

I tried adding the

我尝试添加

if(d.DESCRIPTION == 'null'){ console.log("Its empty"); 

to check if the object returned is empty, but it doesn't work.

检查返回的对象是否为空,但它不起作用。

Can someone explain to me what's wrong with this?

有人可以向我解释这有什么问题吗?

回答by Arun Pratap Singh

Below code(jQuery.isEmptyObject(anyObject)function is already provided) works perfectly fine, no need to write one of your own.

下面的代码(已经提供了jQuery.isEmptyObject(anyObject)函数)工作得很好,不需要自己写一个。

   // works for any Object Including JSON(key value pair) or Array.
  //  var arr = [];
  //  var jsonObj = {};
    if (jQuery.isEmptyObject(anyObjectIncludingJSON))
    {
       console.log("Empty Object");
    }

回答by Kevin B

Just test if the array is empty.

只需测试数组是否为空。

$.getJSON(url,function(json){
    if ( json.length == 0 ) {
        console.log("NO DATA!")
    }
});

回答by Justin Levene

if (!json[0]) alert("JSON empty");

回答by Hassan ALmasri

You can use $.isEmptyObject(json)

您可以使用 $.isEmptyObject(json)

https://api.jquery.com/jQuery.isEmptyObject

https://api.jquery.com/jQuery.isEmptyObject

回答by Ranjith

$.getJSON(url,function(json){
if ( json.length == 0 ) 
{
console.log("NO !")
}
});