javascript 检查 Json 对象是否为空

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

Checking if Json object is empty

javascriptjqueryobject

提问by Andreas Uldall Leonhard

I use Jquery to check if my object from an ajax call is empty or not.

我使用 Jquery 检查来自 ajax 调用的对象是否为空。

In this example I have made a correct AJAX call and it returns some data.

在这个例子中,我做了一个正确的 AJAX 调用,它返回了一些数据。

console.log ("obj before Json parse: ",response);
var test = $.isEmptyObject(response);
console.log("test if object is empty:",test);

obj before Json parse:  [{"dateTime":"2015-10-02","entries":220}]
est if object is empty: false

However in this example I have made an incorrect AJAX call that returns nothing.

然而,在这个例子中,我做了一个不返回任何内容的错误 AJAX 调用。

console.log ("obj before Json parse: ",response);
var test = $.isEmptyObject(response);
console.log("test if object is empty:",test);

obj before Json parse:  []
test if object is empty: false

surely the test variable should be true in this case as the object is empty?

在这种情况下,由于对象为空,测试变量肯定应该为真吗?

回答by Tushar

Use lengthto check if the object is empty or not.

使用length来检查对象是否为空。

var isEmpty = (response || []).length === 0;

回答by Madhusudhan R

var jsonData = JSON.parse(responseBody);
tests['empty_or_not'] = jsonData.length === 0;