Can an array be top-level JSON-text?


Arrays Problem Overview

per the debate in this post: json-conversion-in-javascript

Arrays Solutions

Solution 1 - Arrays

Yes, an array is legal as top-level JSON-text.

There are four standard documents defining JSON: RFC 4627, RFC 7159 (which obsoletes RFC 4627), ECMA-404, and RFC 8259 (which obsoletes RFC 7159, and calls ECMA-404 normative). They differ in which top-level elements they allow, but all allow an object or an array as the top-level element.

  • RFC 4627: Object or array.
    "A JSON text is a serialized object or array."
  • RFC 7159, RFC8259: Any JSON value.
    "A JSON text is a serialized value. Note that certain previous specifications of JSON constrained a JSON text to be an object or an array." Section 2
  • ECMA-404: Any JSON value.
    "A JSON text is a sequence of tokens formed from Unicode code points that conforms to the JSON value grammar."

Solution 2 - Arrays

Yes, but you should consider making the root an object instead in some scenarios, due to JSON hijacking. This is an information disclosure vulnerability based on overriding the array constructor in JavaScript.

Solution 3 - Arrays

This is from the ECMAScript specification.

JSONText :

JSONValue : JSONNullLiteral JSONBooleanLiteral JSONObject JSONArray JSONString JSONNumber

Solution 4 - Arrays

Yes you can do it. Put in [{}]

Solution 5 - Arrays

There is some confusion, seen in the other comments. The "application/json" media type allows only object or array at the top-level for JSON-text, per JSON RFC. However, for a parser any JSON value is acceptable, as seen in the ECMAScript specification.

Update: RFC 4627 is outdated. The new RFC permits also simple values at the top-level. (Thanks, Matthias Dieter Wallnöfer.)


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
QuestionDustin GetzView Question on Stackoverflow
Solution 1 - ArraysDustin GetzView Answer on Stackoverflow
Solution 2 - ArraysMatthew FlaschenView Answer on Stackoverflow
Solution 3 - ArraysChaosPandionView Answer on Stackoverflow
Solution 4 - ArrayshvgotcodesView Answer on Stackoverflow
Solution 5 - Arrayscdunn2001View Answer on Stackoverflow