Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON: key items by id or not?

Tags:

json

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?

like image 578
erjiang Avatar asked Jul 23 '10 16:07

erjiang


1 Answers

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.

like image 156
Gumbo Avatar answered Sep 26 '22 00:09

Gumbo