JSON Arrays
Learning Focus
Arrays are the second structural JSON type. They appear in virtually every API response as the container for multiple records.
What is a JSON Array?
An array is an ordered list of zero or more values wrapped in [].
["apple", "banana", "cherry"]
Elements can be any JSON type — even mixed:
[42, "hello", true, null, {"key": "value"}, [1, 2, 3]]
Common Patterns
Array of Objects (most common in APIs)
{
"users": [
{ "id": 1, "name": "Alice", "role": "admin" },
{ "id": 2, "name": "Bob", "role": "editor" },
{ "id": 3, "name": "Carol", "role": "viewer" }
]
}
Nested Arrays (matrix)
{ "matrix": [[1,0,0],[0,1,0],[0,0,1]] }
Array of Primitives
{
"permissions": ["read", "write", "delete"],
"scores": [98, 87, 92, 75]
}
Empty Array
Prefer [] over null for empty collections:
{ "tags": [] }
jq — Array Operations
echo '[10,20,30,40]' | jq '.[0]' # 10 — first
echo '[10,20,30,40]' | jq '.[-1]' # 40 — last
echo '[1,2,3,4,5]' | jq '.[1:3]' # [2,3] — slice
echo '[1,2,3]' | jq 'length' # 3
echo '[1,2,3]' | jq '.[]' # iterate
Language Mappings
| Language | JSON Array Maps To |
|---|---|
| JavaScript | Array |
| Python | list |
| Go | slice ([]T) |
| PHP | Indexed array |
| Ruby | Array |
Concept Map
Concept Flow
JSON Array → Ordered Elements
├── Homogeneous (same type) → API result sets, collections
└── Heterogeneous (mixed) → Flexible tuples
Common Pitfalls
| Pitfall | Consequence | Prevention |
|---|---|---|
null for empty collection | Client must null-check before iterating | Default to [] |
| Assuming stable index positions | Breaks if server reorders | Use IDs for lookup, not position |
| Trailing comma after last element | Parse error | Remove trailing commas |
| Deep nesting without schema | Hard to maintain | Define JSON Schema for complex arrays |
What's Next
- Previous: JSON Objects — Review the key-value container.
- Next: JSON Schema — Validate and document JSON structure.
- Section Overview — Return to the Data Types module index.