views:

74

answers:

2

In a JQuery getJSON call, how can I tell the length of the JSON that's returned?

function refreshRoomList() {
    $.getJSON('API/list_rooms',
          function (rooms) {
              if (rooms.length > 0) {
                  $("#existing-room-list").empty();
                  $("#join-existing-room").text("Join existing room:"); // this shouldn't be here
                  $.each(rooms, function (index, roomName) {
                      var newChild = sprintf('<li><a href="room?key=%s">%s</a></li>', index, roomName);
                      $("#existing-room-list").append(newChild);
                  });
              }
              else {
                  $("#join-existing-room").text("No rooms found.");
              }
          });
}

For some reason this doesn't work, but if I replace rooms.length > 0 with true, the full list of rooms is printed out.

If rooms is empty, it is returned as {}.

A: 

Try this approach instead, in your situation it should be null when empty:

if (rooms) {
Nick Craver
This looks like it's working in my minimal initial testing. Thanks.
Rosarch
@Rosarch: I think you'll need more testing ;)
Crescent Fresh
+3  A: 

If rooms is empty, it is returned as {}.

Thus, it's not an array, but an object. Objects doesn't have a length. There's only one of it. If you want to denote nothing, then rather use null instead of {}. This way you can use if (rooms) instead.

To learn more about JSON, you may find this article useful.

BalusC