1

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");
 }
1
  • 3
    It's an array, so just check for length Commented Mar 10, 2014 at 13:27

2 Answers 2

5

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"); 
}
Sign up to request clarification or add additional context in comments.

6 Comments

if you store your json in a JsonData variable, then JsonData.cities is the array
you have a start?centre=1: 103 at the end of your json. this makes the whole json invalid (paste and copy your structure on jsonlint.com)
then I think you need to provide a fiddle that reproduces the error. I can't imagine what else is going wrong here
{"cities":[{"id":0,"client_id":"1","storename":"test","notes":"test","rejected":"on","offer":"test","time":1394458602054},{"id":1,"client_id":"1","storename":"","notes":"","rejected":"on","offer":"","time":1394458606774}]} This was logged when i did console.log(JsonData); and it said there was no data .
could you try to console.log(typeof JsonData)?
|
0

check for cities.length its an array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.