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?
meeting
should always be an array, even if you only have one or even zero items in it. This will save you a lot of trouble, because you don't have to distinguish betweet two possiblities. It's also the more consistent way to do it. – basilikum Jul 16 '13 at 11:53