Ema.H
Ema.H

Reputation: 2878

What is the best format to return array in JSON response?

I'm asking about the best practice to return data array in a JSON response...

Like this :

{ myObjectContainsArray: [ {object1}, {object2}, {object3}] }

// and get it like this => myObjectContainsArray[0].object1property 

Or :

[{object1}, {object2}, {object3}]
// and get it like this => [0].object1property 

What is the best way ?

Thanks

Upvotes: 0

Views: 869

Answers (1)

deceze
deceze

Reputation: 522165

There's a potential cross-site vulnerability when returning plain arrays, described here: https://haacked.com/archive/2009/06/25/json-hijacking.aspx/

It turns out that a script that contains a JSON array is a valid JavaScript script and can thus be executed. A script that just contains a JSON object is not a valid JavaScript file. For example, if you had a JavaScript file that contained the following JSON:

{"Id":1, "Balance":3.14}

And you had a script tag that referenced that file:

<script src="http://example.com/SomeJson"></script>

You would get a JavaScript error in your HTML page. However, through an unfortunate coincidence, if you have a script tag that references a file only containing a JSON array, that would be considered valid JavaScript and the array gets executed. [..]

Therefore it's recommended to only return objects.

Upvotes: 2

Related Questions