0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is largely a non-issue these days: fetch.spec.whatwg.org/#corb
Thanks a lot, have a nice day :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.