JSON: key items by id or not?

Viewed 3836

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?

4 Answers

These are different use cases, the standard should be as the second and in some cases, the first one. When ? when you want to access by key and avoid looping thru. Probably the first case should be for internal use only, and the second one (current standard) for external exposure. Both valid.

Note that the former one puts it's objects inside an object {} while the latter puts them into an array []. Putting them in an array could be used if you need all the items. And the former one could be used if you would like to access them with the id.

Related