$.getJSON(url, function(json) { var output = ''; $.each(json, function(i,d) { if(d.DESCRIPTION == 'null'){ console.log("Its empty"); } var description = d.DESCRIPTION; output += '<tr><td>'+d.NAME+'</td><td>'+'<tr><td>'+d.DESCRIPTION+'</td><td>'; }); });
I tried adding the
if(d.DESCRIPTION == 'null'){ console.log("Its empty");
to check if the object returned is empty, but it doesn't work.
Can someone explain to me what's wrong with this?
If you want to check if your response is not empty try : if ( json. length == 0 ) { console. log("NO DATA!") }
jQuery isEmptyObject() methodThe isEmptyObject() method is used to determine whether the passed argument is an empty object or not. It returns a Boolean value. If it finds the passed value is an empty object, it returns true. Otherwise, it returns false.
jquery json provide several method for getting key value or check if key exists etc. In this example we will use hasOwnProperty method of json object that will help to check if key exists or not in jquery. hasOwnProperty return true if key is exists and return false if key is not exists on given javascript json.
Below code(jQuery.isEmptyObject(anyObject) function is already provided) works perfectly fine, no need to write one of your own.
// works for any Object Including JSON(key value pair) or Array. // var arr = []; // var jsonObj = {}; if (jQuery.isEmptyObject(anyObjectIncludingJSON)) { console.log("Empty Object"); }
Just test if the array is empty.
$.getJSON(url,function(json){ if ( json.length == 0 ) { console.log("NO DATA!") } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With