Skip to main content

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

LanguageJSON Array Maps To
JavaScriptArray
Pythonlist
Goslice ([]T)
PHPIndexed array
RubyArray

Concept Map

Concept Flow

JSON Array → Ordered Elements
├── Homogeneous (same type) → API result sets, collections
└── Heterogeneous (mixed) → Flexible tuples

Common Pitfalls

PitfallConsequencePrevention
null for empty collectionClient must null-check before iteratingDefault to []
Assuming stable index positionsBreaks if server reordersUse IDs for lookup, not position
Trailing comma after last elementParse errorRemove trailing commas
Deep nesting without schemaHard to maintainDefine JSON Schema for complex arrays

What's Next