Whenever data comes in multiples, such as a list of products, a feed of posts, or a batch of sensor readings, JSON expresses it with an array. Arrays are the second of the two structural types in JSON, and mastering them means mastering iteration over API data. In this lesson of our JSON tutorial series, we cover array syntax, common shapes, and the patterns you will use to transform them.
An array is an ordered sequence of values inside square brackets, separated by commas:
["red", "green", "blue"]Unlike object keys, array order is guaranteed and meaningful. The first element stays first through serialization, transfer, and parsing.
Any JSON value can be an element: strings, numbers, booleans, null, objects, and other arrays.
{
"mixed": [42, "text", true, null],
"matrix": [[1, 2], [3, 4]],
"users": [
{ "id": 1, "name": "Ada" },
{ "id": 2, "name": "Alan" }
]
}The users shape, an array of similarly structured objects, is by far the most important pattern in practice. Nearly every list endpoint in every REST API returns it.
Array elements are accessed by zero-based index after parsing:
const data = JSON.parse('{"users":[{"name":"Ada"},{"name":"Alan"}]}');
console.log(data.users[0].name); // "Ada"
console.log(data.users.length); // 2Accessing an index that does not exist returns undefined in JavaScript rather than throwing, so check length before trusting a position.
Three methods handle most day-to-day work with parsed JSON arrays:
const names = data.users.map(u => u.name); // ["Ada", "Alan"]
const active = data.users.filter(u => u.active);
const total = orders.reduce((sum, o) => sum + o.amount, 0);A JSON document may be a bare array such as [1, 2, 3] with no wrapping object. Many APIs avoid this and wrap lists in an object like { "items": [...] } instead. The wrapper leaves room to add metadata later, such as pagination fields like total and nextPage, without breaking existing clients.
[1, 2, 3,] is invalid JSON, as covered in the syntax lesson.Next up: JSON vs XML, where we compare the two great data formats and see why JSON usually wins.