JSON Response from REST Calls: Object vs Array

27296

Please excuse my ignorance re JSON responses. 

This question is limited to the iSheet REST API calls but may apply to the REST API for other areas. I have noticed when I make a REST call that can return 0, 1 or N results -- such as retrieving the records in an iSheet -- if the response includes N results, then the JSON response formats that as an array, but if there is only 1 response, then the JSON response is formatted as an object (not an array).  This requires me to include defensive coding when I parse the JSON response to check whether or not the response returns an array or object.   That likely means no responses would be an empty array, but that may be handled more gracefully.

Shouldn't the response format be consistent -- and be an array -- regardless of whether there is 1 or N results?  See:  softwareengineering.stackexchange.com/.../api-always-returns-jsonobject-or-jsonarray-best-practices: "If it is retrieving one or more objects, it makes logical sense to always return an array containing the results, even if it is an array with only one element."

  • We have also had to create a few exception handlers recently to tackle this issue

  • Mitch Grant I suspect that this may be caused because on the backend the results are generated as XML and then are dynamically converted to JSON. Because XML does not have arrays, the conversion acts differently depending on whether there is 1 result or multiple.

  • Mark Salamon, absolutely correct - a common problem. Without an XSD, the parser would have no idea that a single child node is in fact an array of one. A simple pre-process ternary in JS can simplify things:

       // ...
       // ...
    
       res.isheet.data.item = Array.isArray(res.isheet.data.item) 
          ? res.isheet.data.item
          : [res.isheet.data.item
    // ... // ... ]]>
  • I noticed this too. I find it so annoying, and it is the only reason making me return data as XML (where it is consistent) rather than JSON (which all apps should be consuming these days) for HighQ api calls.

  • HighQ, I think you could fix this in the way that Andrew Quinn indicated and it LIKELY should not break any existing code, because any code should be expecting an array (and may have defensive code looking for an object). It just means that the defensive code will not end up being used.