Is a list/array valid JSON?

JavascriptJson

Javascript Problem Overview


I wish to write a webservice which serves lists of JSON objects. Is it valid JSON to return the following:

[  {"keyA1":"valA", "keyB1":"valB"} ,{"keyA2":"valA", "keyB2":"valB"} ,{"keyA3":"valA", "keyB3":"valB"}]

Or is the "right" way to do it to put it in a single object to return:

{"elements":[
   {"keyA1":"valA", "keyB1":"valB"}
  ,{"keyA2":"valA", "keyB2":"valB"}
  ,{"keyA3":"valA", "keyB3":"valB"}
]}

Javascript Solutions


Solution 1 - Javascript

Both forms are valid. However, for an API, I would recommend the second form. The reason is that it gives you a path for expansion of your API.

For example, if you have an API getUsersInGroup which returns an array of user objects, and later you decide you want to include, say, some aggregate statistics about the users being returned, there's no easy way to do that without breaking existing clients (or including lots of redundant data in each user object). If you use an object, you simply add another field to the object which is silently ignored by clients on a previous version of the API.

In short, try to avoid top-level primitives wherever possible in your API, and you'll find it easier to expand in the future.

Solution 2 - Javascript

Both are valid JSON, but the second way is correct; passing JSON around as an array can lead to security vulnerabilities. See a related post on JSON security to learn more about this. In some frameworks, such as flask, there are even measures that prevent you from passing around JSON as an array.

Solution 3 - Javascript

You can validate JSON using http://jsonlint.com/

Both are valid JSON results but I'd use the second one. It's more logical and descriptive.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionloneboatView Question on Stackoverflow
Solution 1 - JavascriptChris HayesView Answer on Stackoverflow
Solution 2 - JavascriptJDongView Answer on Stackoverflow
Solution 3 - JavascriptSergei BeregovView Answer on Stackoverflow