Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if JSON return is empty with jquery

$.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?

like image 668
BaconJuice Avatar asked Jan 15 '13 19:01

BaconJuice


People also ask

How check JSON result is empty?

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

Is Empty object jquery?

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.

How do you check key is exist or not in JSON?

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.


2 Answers

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");     } 
like image 79
Arun Pratap Singh Avatar answered Sep 28 '22 03:09

Arun Pratap Singh


Just test if the array is empty.

$.getJSON(url,function(json){     if ( json.length == 0 ) {         console.log("NO DATA!")     } }); 
like image 42
Kevin B Avatar answered Sep 28 '22 03:09

Kevin B