4

I have the following JSON:

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

I'm interested in objects: I want to know if objects is empty and show an alert:

something like this:

success: function (data) {
    $.each(data.objects, function () {
        if data.objects == None alert(0)
        else :alert(1)
    });
ComFreek
  • 29,044
  • 18
  • 104
  • 156
GrantU
  • 6,325
  • 16
  • 59
  • 89

6 Answers6

9

i don't know what is you meaning about empty object, but if you consider

{}

as a empty object, i suppose you use the code below

var obj = {};

if (Object.keys(obj).length === 0) {
    alert('empty obj')
}
GilbertSun
  • 600
  • 5
  • 9
8

Use Array's length property:

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

if (data.objects.length == 0) {
  alert("Empty");
}
else {
  alert("Not empty");
}
ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • There are more robust answers than this. It's actually better to leave off the `== 0` because if `objects` is not array you'll get unexpected results. @GrantU consider checking the others. – tybro0103 Nov 01 '13 at 17:00
  • @tybro0103 I don't think so. The check is unnecessary if the server always includes the `objects` key as an array in the JSON output. – ComFreek Nov 01 '13 at 17:06
  • I guess it depends on how much you trust the server – tybro0103 Nov 01 '13 at 20:16
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.

tybro0103
  • 48,327
  • 33
  • 144
  • 170
2

You can use the length property to test if an array has values:

if (data.objects.length) {
    $.each(data.objects, function() {
        alert(1)
    });
} 
else {
    alert(0);
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

this was what i did, thanks @GilbertSun, on a jsonp callback when I got an undefined with data.objects.length

success: function(data, status){
                  if (Object.keys(data).length === 0) {
                      alert('No Monkeys found');
                    }else{     
                      alert('Monkeys everywhere');
                    }
    }
Justis Matotoka
  • 809
  • 6
  • 3
-1

Js

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

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

Only jQuery:

$(myJson).isEmptyObject(); //Return false
$({}).isEmptyObject() //Return true
Guilherme Soares
  • 726
  • 3
  • 7
  • 19