检查JSON对象是否为空

时间:2014-03-10 13:25:38

标签: javascript jquery json

我想检查一个对象是否在城市内部有任何数据,所以基本上它会显示为数据的真实情况:

JSON

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

并为此假:

{"cities":[]} 

目前我的代码不正确,因为它没有检查城市内部是否为空,是否有任何方式我可以调整我的代码使其工作?

的JavaScript

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

2 个答案:

答案 0 :(得分:4)

假设JsonData是有效的JSON

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

如果JsonData是一个字符串,则需要使用JSON.parse(JsonData)将其作为JSON结构进行解析:请参阅MDN以获取进一步的参考


注意: 如果您不确定始终有JsonDataJsonData.cities可用,则可以通过这种方式为属性查找创建围栅(如ajaxian所示)

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

答案 1 :(得分:0)

检查cities.length它的数组。