4

我有以下 JSON:

{
    "meta": {
        "limit": 20,
        "next": null,
        "offset": 0,
        "previous": null,
        "total_count": 0
    },
    "objects": []
}

我对对象感兴趣:我想知道对象是否为空并显示警报:

像这样的东西:

success: function (data) {
    $.each(data.objects, function () {
        if data.objects == None alert(0)
        else :alert(1)
    });
4

6 回答 6

8

使用数组的长度属性:

// note: you don't even need '== 0'

if (data.objects.length == 0) {
  alert("Empty");
}
else {
  alert("Not empty");
}
于 2013-11-01T15:49:16.210 回答
8

我不知道你对空对象是什么意思,但如果你考虑

{}

作为一个空对象,我想你使用下面的代码

var obj = {};

if (Object.keys(obj).length === 0) {
    alert('empty obj')
}
于 2013-11-01T17:41:24.893 回答
6

This is the best way:

if(data.objects && data.objects.length) {
  // not empty
}

And it's the best for a reason - it not only checks that objects is not empty, but it also checks:

  1. objects exists on data
  2. objects is an array
  3. objects is a non-empty array

All of these checks are important. If you don't check that objects exists and is an array, your code will break if the API ever changes.

于 2013-11-01T15:52:06.710 回答
2

您可以使用该length属性来测试数组是否具有值:

if (data.objects.length) {
    $.each(data.objects, function() {
        alert(1)
    });
} 
else {
    alert(0);
}
于 2013-11-01T15:49:16.750 回答
1

这就是我所做的,感谢@GilbertSun,当我得到一个未定义的 data.objects.length 时,在 jsonp 回调中

success: function(data, status){
                  if (Object.keys(data).length === 0) {
                      alert('No Monkeys found');
                    }else{     
                      alert('Monkeys everywhere');
                    }
    }
于 2014-10-15T10:03:39.223 回答
-1

JS

var myJson = {
   a:[],
   b:[]
}

if(myJson.length == 0){
   //empty
} else {
  //No empty
}

只有 jQuery:

$(myJson).isEmptyObject(); //Return false
$({}).isEmptyObject() //Return true
于 2013-11-01T15:57:16.347 回答