Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a list/array valid JSON? [duplicate]

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"} ]} 
like image 981
loneboat Avatar asked Oct 27 '13 20:10

loneboat


People also ask

Is an array a valid JSON response?

You can validate JSON using an application like JSONLint. JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON.

Is JSON an array or list?

JSON Syntax JSON defines only two data structures: objects and arrays. An object is a set of name-value pairs, and an array is a list of values. JSON defines seven value types: string, number, object, array, true, false, and null.

Can JSON have duplicate values?

We can have duplicate keys in a JSON object, and it would still be valid.

Is a list of strings valid JSON?

So let's break the name here to understand better. JSON is JavaScript Object Notation is used for data interchange, Array of strings is an ordered list of values with string type. So on a whole, the 'JSON array of strings' represents an ordered list of values, and It can store multiple values.


2 Answers

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.

like image 115
Chris Hayes Avatar answered Sep 18 '22 19:09

Chris Hayes


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.

like image 30
JDong Avatar answered Sep 21 '22 19:09

JDong