jthe jthe - 6 months ago 22
JSON Question

JSON list optimization

I want to create a JSON API that returns a list of objects. Each object has an id, a name and some other information. API is consumed using JavaScript.

The natural options for my JSON output seems to be:

"myList": [
{
"id": 1,
"name": "object1",
"details": {}
},
{
"id": 2,
"name": "object2",
"details": {}
},
{
"id": 3,
"name": "object3",
"details": {}
},
]


Now let's imagine that I use my API to get all the objects but want to first do something with id2 then something else with id1 and id3.

Then I may be interested to be able to directly get the object for a specific id:

"myList": {
"1": {
"name": "object1",
"details": {}
},
"2": {
"name": "object2",
"details": {}
},
"3": {
"name": "object3",
"details": {}
},
}


This second option may be less natural when somewhere else in the code I want to simply loop through all the elements.

Is there a good practice for these use cases when the API is used for both looping through all elements and sometime using specific elements only (without doing a dedicated call for each element)?

Answer

In your example you've changed the ID value from 1 to id1. This would make operating on the data a bit annoying, because you have to add and remove id all the time.

If you didn't do that, and you were relying on the sorted order of the object, you may be in for a surprise, depending on JS engine:

var source = JSON.stringify({z: "first", a: "second", 0: "third"});
var parsed = JSON.parse(source);
console.log(Object.keys(parsed));
// ["0", "z", "a"]

My experience is to work with arrays on the transport layer and index the data (i.e. convert array to map) when required.

Comments