8

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,363
  • 3
  • 45
  • 73
rocket
  • 223
  • 1
  • 2
  • 10

3 Answers3

20

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,327
  • 2
  • 22
  • 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
2

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
  • 5,818
  • 1
  • 24
  • 42
1

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