Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Source Link
Tom
  • 65
  • 1
  • 5

json object vs array of objects

I'm querying a remote server and receiving a json reponse. The format of the reponse depends on the number of objects in the response. If there is a single object it looks similar to:

"results": {
  "meeting": {
    "location": "Location A",
    "time": "1378033200"
  }
}

But if there is more then one object in the response, I get an array of objects instead:

"results": {
  "meeting": [
    {
      "location": "Location A",
      "time": "1378033200"
    },
    {
      "location": "Location B",
      "time": "1379250000"
    }
  ]
}

The complete response from the server includes a "count" variable, so I can distinguish between the two situations. In my Javascript at the moment I first check the count, and if there is exactly one object, I read out the location and time information similar to:

var location = results.meeting.location;
var time = results.meeting.time;

If there is anything other than exactly one object, I do

for(var i=0; i<count; i++) {
  var location = results.meeting[i].location;
  var time = results.meeting[i].time;
}

This works, but I'm wondering if there is a more elegant way of handling the two situations?