tags:

views:

23

answers:

2

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?

+1  A: 

If you want to access the object via the ID, use the former variant with the ID as property name. Then you can directly access that object using the object’s ID. Otherwise, if you need to work with all objects anyway, use the latter variant.

Gumbo
I don't really know how clients will use this data yet.
erjiang
+1  A: 

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.

Swizec Teller