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)
    });
1
  • Are you controlling the server-side code that generates the JSON? If so, just set some property equal to zero. Commented Nov 1, 2013 at 15:50

6 Answers 6

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

Comments

8

Use Array's length property:

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

if (data.objects.length == 0) {
  alert("Empty");
}
else {
  alert("Not empty");
}

3 Comments

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 I don't think so. The check is unnecessary if the server always includes the objects key as an array in the JSON output.
I guess it depends on how much you trust the server
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.

Comments

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);
}

Comments

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');
                    }
    }

Comments

-1

Js

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

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

Only jQuery:

$(myJson).isEmptyObject(); //Return false
$({}).isEmptyObject() //Return true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.