Require the JSON top-level value to be an array or object.
The JSON specification technically allows any JSON value (object, array, string, number, boolean, or null) to be used as the top-level element of a JSON document. However, some older JSON parsers, especially those created before RFC 7158/4627 was fully adopted, only support objects or arrays as the root element.
Additionally, some security practices (such as those preventing JSON hijacking attacks) rely on the assumption that the top-level value is an object or array. Using an object or array at the top level also provides better extensibility for your data structures over time.
This rule warns when the top-level value in the document is neither an array nor an object. This can be enabled to ensure maximal interoperability with the oldest JSON parsers.
Examples of incorrect code for this rule:
Examples of correct code for this rule:
/* eslint json/top-level-interop: "error" */
{
"property": "value",
"otherProperty": 123
}
["element", "anotherElement"]
{}
[]You might want to disable this rule if:
- You know that all consumers of your JSON data support primitive values at the root level.
- You're working with JSON5 or other JSON-like formats that have different constraints.
- You're specifically using JSON to represent a single value within a constrained system where the receivers expect primitive values.
- You're generating JSON for internal use where interoperability with older parsers is not a concern.