javascript 检查 JSON 响应数据是否为空

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

Check if JSON response data is empty

javascriptangularjs

提问by rocket

The JSON response looks like this when it is empty when viewed in the browser console:

在浏览器控制台中查看时,JSON 响应为空时如下所示:

{"data":{},"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://url/form/BN217473","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"","xhrStatus":"complete"}

In angular script I am checking if the response is empty but the check is not catching the empty response as the logic block is never executed

在 angular 脚本中,我正在检查响应是否为空,但检查未捕获空响应,因为逻辑块从未执行

if (response.data == '') {
    console.log("no data found");
}

How can I check that my response is not empty?

如何检查我的回复是否为空?

回答by Sagar Kharche

Try below code snippet:-

试试下面的代码片段:-

if(!Object.keys(response.data).length){
     console.log("no data found");
 }

If you are getting data as empty object like data: {}, then you should check if there is any key inside the object or not.

如果您将数据作为像 data: {} 这样的空对象获取,那么您应该检查对象内是否有任何键。

回答by Chris Gunawardena

You can check the number of keys/properties with Object.keys(response.data).length === 0or less efficiently with JSON.stringify({}) == JSON.stringify(response.data)

您可以使用以下方法检查键/属性的数量 Object.keys(response.data).length === 0或效率较低JSON.stringify({}) == JSON.stringify(response.data)

回答by Virgile Junique

If you want to check if your response is not empty try :

如果您想检查您的回复是否为空,请尝试:

    if ( json.length == 0 ) {
    console.log("NO DATA!")
}

But i advice you to use lodashand his isNil()method or isEmpty()to check if your object is empty or null or undefined.

但我建议您使用lodash和他的isNil()方法,或者isEmpty()检查您的对象是否为空、null 或未定义。

Cheeers

干杯