Web Development – Proper JSON Structure for Front-End Consumption

javascriptjsonweb-development

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?

Best Answer

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" : [...]
      }
   }