4

Having worked on several different web application code bases, I've seen some divergence in how back-ends serving JSON to front-ends structure that data. In particular, when a backend wants to return a number of objects of the same structure. Do you just wrap up all of the objects in an array? What about the "key" of the first array? What should that be?

For example, say my back end wants to return a number of "image" items. Each image item is structured like this:

{
    "id" : 123,
    "filename" : "someFile.jpg",
    "caption" : "some image or other",
    "gallery" : 123
}

How would I structure a grouping of these items properly for consumption by a javascript front-end?

rgb
  • 879
  • 2
  • 8
  • 18
  • I don't think there's a 'properly' here so long as its valid JSON. Its going to depend on what the client needs. Does the client need the data in a specific order? Or can it come through in any order? – GrandmasterB Mar 06 '14 at 19:29

2 Answers2

9

Coming from a front-end developer perspective, I prefer simple and semantic as much as possible. Generally inside a consistent envelope for debugging and tracking, the actual data would be as follows:

{
    "images" : [
        {
          "id" : 123,
          "filename" : "someFile.jpg",
          "caption" : "some image or other",
          "gallery" : 123
        },{
          "id" : 124,
          "filename" : "someFile.jpg",
          "caption" : "some image or other",
          "gallery" : 124
        }
    ]
}

Envelopes often look something like this:

   {      
      "messageID"     : "sflskdfj-asldkja-asdlk", // some uuid
      "sendDate"      : 1394134506764, // time at which the server sent the message
      "requestMethod" : "GET",
      // whatever else you want for front-end tracking or debugging
      "data"          : {
          "images" : [...]
      }
   }
Fresheyeball
  • 250
  • 1
  • 10
0

Coming from rails and it auto-magical ability to transform ruby object into XML JSON... I would say that you should just send an array of your entities. If you are worring about not knowing what could be inside the array. Should you be using a RESTful approach, the URL:HTTP_VERB pair will be telling you the resource you are accessing and what to expect from the response.

mimsugara
  • 221
  • 3
  • 4