Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to test if response JSON array is empty

Tags:

json

jquery

I'm getting back the following JSON:

{"array":[],"object":null,"bool":false}

And I'm testing it with the following, seemingly exhaustive, if statement:

$.ajax({
        type: "GET",
        url: "/ajax/rest/siteService/list",
        dataType: "json",
        success: function (response) {
            var siteArray = response.array;

            // Handle the case where the user may not belong to any groups
            if (siteArray === null || siteArray=== undefined || siteArray=== '' || siteArray.length === 0) {
                            window.alert('hi');
            }
       }
});

But the alert is not firing. :[

like image 964
Lurk21 Avatar asked May 03 '13 02:05

Lurk21


People also ask

How check response JSON is empty?

If you want to check if your response is not empty try : if ( json. length == 0 ) { console. log("NO DATA!") }

How do I check if an array is empty in JavaScript?

The array can be checked if it is empty by using the array. length property. This property returns the number of elements in the array. If the number is greater than 0, it evaluates to true.

How do you check array is empty or not in react JS?

To check if an array is empty in React, access its length property, e.g. arr. length . If an array's length is equal to 0 , then it is empty. If the array's length is greater than 0 , it isn't empty.

Can you have an empty array in JSON?

JSON data has the concept of null and empty arrays and objects.


2 Answers

Use $.isArray() to check whether an object is an array. Then you can check the truthness of the length property to see whether it is empty.

if( !$.isArray(siteArray) ||  !siteArray.length ) {
    //handler either not an array or empty array
}
like image 72
Arun P Johny Avatar answered Sep 20 '22 15:09

Arun P Johny


Two empty arrays are not the same as one another, for they are not the same object.

var a = [];
if (a === []){
  // This will never execute
}

Use if (siteArray.length==0) to see if an array is empty, or more simply if (!siteArray.length)

like image 41
Phrogz Avatar answered Sep 16 '22 15:09

Phrogz