JSON Arrays Overview
JSON arrays group valid JSON data types together. A JSON array may contain any valid JSON data type, and may also contain duplicate values. This article covers valid data types in the next section.
Define JSON arrays by surrounding lists of JSON data types with square brackets. Separate every value in the JSON array with a comma. You may use any amount of whitespace you wish, including newline characters, to separate values.
The following JSON arrays are equivalent.
["A", "B", "C", "D"] [ "A", "B", "C", "D" ]
JSON Array Data Types
JSON arrays can hold information in six basic data types:
- String: Zero or more Unicode characters surrounded by quotation marks.
- Number: Whole or decimal number. It may be signed, may contain a fractional part, and may use exponential E notation.
- Boolean: True or false value, specified by the keywords true or false.
- Null: An empty value, specified by the keyword null.
- Object: Collection of key-value pairs. Objects are declared with curly braces. Keys and values are separated by colons, while key-value pairs are separated by commas. Every key within an object must be unique.
- Array: Ordered list of zero or more elements of any data type, including null values, objects, and duplicates. Arrays are declared with square brackets and elements are separated by commas.
Nesting JSON Arrays
JSON arrays can hold other JSON arrays inside of them, a technique called “nesting.” This is a common strategy for data architecture when creating grids or tables of information.
// A JSON table containing 3 rows with 4 columns each [ ["A", "B", "C", "D"], ["E", "F", "G", "H"], ["I", "J", "K", "L"] ]
Each nesting of a JSON array is called a “dimension.” Assuming an array has “n” dimensions, the standard way of referring to nested JSON arrays is that they are “n-dimensional.”
The previous example is 2-dimensional, but there is no limit to the number of dimensions a nested JSON array may contain. For readability and maintenance purposes, it is usually easiest to restrict dimensions to 3 or less. The following 3-dimensional example shows how complicated multidimensional JSON arrays can become, even with indenting and added spacing for readability.
// A JSON 3-dimensional array [ [ ["A", "B", "C", "D"], ["E", "F", "G", "H"], ["I", "J", "K", "L"] ], [ ["1", "2", "3", "4" ], ["5", "6", "7", "8" ], ["9", "10", "11", "12"] ] ]
JSON arrays group data together within JSON objects and are a critical JSON data type. They can be structured as simple lists, 2-dimensional tables, or complex multidimensional arrays.
Enroll in our Intro to Programming Nanodegree Program today to learn more about JSON arrays and other programming concepts.