1

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)?

1
  • How to read the JSON with any language/framework is of no importance here. I just want to discuss optimization for lists in JSON. Commented May 26, 2016 at 12:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I am trying to understand but it seems you have done the contrary here: using object on the transport layer and getting an array after? I have updated my question removing the "idX" has I get it is condusing.
The example code in my answer is supposed to show you that the order you put data in [z, a, 0] is not necessarily the order you got out [0, z, a]. So if you're working with ordered lists, don't rely on objects.
Oh great I get it. So your answer is that it is preferable to expose arrays for an API. Then you can still map each element when using the API if necessary. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.