Brent
Brent

Reputation: 2485

Check if JSON object is empty

I want to check if an object has any data in it inside of cities, so basically it would show true for data for this:

JSON

{"cities":[{"id":0,"client_id":"1","storename":"test","notes":"test","rejected":"on","offer":"test","time":1394457477525}]} 

and false for this:

{"cities":[]} 

Currently my code is incorrect as its not checking inside of cities just if its empty or not, is there any way I can adapt my code for it to work?

JavaScript

 if (jQuery.isEmptyObject(JsonData) == false) {
      $('#upload').show();
      alert("There is data");
 } else {
      $('#upload').hide();  
      alert("There is no data");
 }

Upvotes: 1

Views: 2300

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

Assuming JsonData is a valid JSON

if (JsonData.cities.length > 0) {
   alert("there is data");  
}
else {
   alert("there is no data"); 
}

if JsonData is a string you need instead to parse it before as a JSON structure, using JSON.parse(JsonData) : see MDN for further reference


Note: If you're not sure to always have JsonData or JsonData.cities available, you may create a fence for properties lookup (as suggested on ajaxian) in this way

if (((JsonData || 0).cities || 0).length > 0) {
   alert("there is data");  
}
else {
   alert("there is no data"); 
}

Upvotes: 5

Ritesh Chandora
Ritesh Chandora

Reputation: 8640

check for cities.length its an array.

Upvotes: 0

Related Questions