Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if Json object is empty

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

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

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.

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?

like image 615
Andreas Uldall Leonhard Avatar asked Mar 14 '26 07:03

Andreas Uldall Leonhard


1 Answers

Use length to check if the object is empty or not.

var isEmpty = (response || []).length === 0;
like image 88
Tushar Avatar answered Mar 16 '26 21:03

Tushar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!