11

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

{"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

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

How can I check that my response is not empty?

jordiburgos
  • 5,964
  • 4
  • 46
  • 80
rocket
  • 253
  • 1
  • 2
  • 13

3 Answers3

27

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.

Sagar Kharche
  • 2,577
  • 2
  • 24
  • 34
  • Doesn't work for me. Content is `{}` but the check fails. Length is 2. – testing Jun 17 '19 at 16:16
  • 2
    OK, you have to use an object and not a string. So `JSON.parse(someString)` is your friend. But `JSON.parse()` can fail ... – testing Jun 18 '19 at 09:40
  • If you want to use single method for checking strings and json strings for null or empty, you can try this: public static boolean isNotNullOrEmpty(Object str) { if (str == null) { return false; } else { if ("".equals(str)) { return false; }else if("{}".equals(str)) { return false; } } return true; } – Amulya Koppula Nov 07 '22 at 15:19
3

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

Chris Gunawardena
  • 6,246
  • 1
  • 29
  • 45
2

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 lodash and his isNil() method or isEmpty() to check if your object is empty or null or undefined.

Cheeers