Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
134
rated 0 times [  140] [ 6]  / answers: 1 / hits: 41220  / 11 Years ago, sun, october 27, 2013, 12:00:00

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}
]}

More From » json

 Answers
2

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.


[#74698] Friday, October 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kamryn

Total Points: 645
Total Questions: 100
Total Answers: 118

Location: Tanzania
Member since Wed, Feb 24, 2021
3 Years ago
kamryn questions
Sun, Apr 10, 22, 00:00, 2 Years ago
Sun, Oct 3, 21, 00:00, 3 Years ago
Thu, May 28, 20, 00:00, 4 Years ago
Tue, May 12, 20, 00:00, 4 Years ago
;