I’ve been charged with creating a simple data source so clients can retrieve a list of things by JSON. Each thing has an ID, so my first impulse was to create something like
{
"13": {
"name": "foo",
"height": 17
},
"18": {
"name": "bar",
"height": 22
}
...
}
But I’ve been told that this is an abuse of JS properties as an associative array, so that something like this would be more appropriate:
[
{
"id": 13,
"name": "foo",
"height": 17
},
{
"id": 18,
"name": "bar",
"height": 22
}
]
The second version just seems… difficult. What’s the best practice here?
The common way of doing it is the latter and there are virtually no benefits from doing the former. At most you’ve saved the consumer of your API about five keystrokes, at worst you created an API that is far less than self explanatory. i.e. Is that key the item’s Id? Is it some other sort of identifier? Is it unique only for this request? Etc.