3

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?

  • 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 6 '14 at 19:29
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" : [...]
      }
   }
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.