A JSON array is an ordered list enclosed in square brackets:
{
"data": [1, 2, 3, 4, 5]
}
Arrays can contain any JSON value type: numbers, strings, booleans, objects, arrays, or null.
Basic Array Syntax
Array of numbers:
{ "scores": [95, 87, 92, 88] }
Array of strings:
{ "tags": ["javascript", "json", "web"] }
Array of booleans:
{ "flags": [true, false, true] }
Array of objects:
{
"users": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]
}
Mixed types (valid but discouraged):
{ "mixed": [1, "text", true, null] }
Accessing Array Elements
In JavaScript, arrays are zero-indexed:
const data = {
"numbers": [10, 20, 30]
};
console.log(data.numbers[0]); // 10
console.log(data.numbers[1]); // 20
console.log(data.numbers[2]); // 30
Common Patterns
List of users:
{
"users": [
{
"id": 1,
"name": "Alice",
"email": "alice@example.com"
},
{
"id": 2,
"name": "Bob",
"email": "bob@example.com"
}
]
}
Paginated data:
{
"data": [...],
"page": 1,
"pageSize": 10,
"total": 100
}
Time series data:
{
"measurements": [
{ "timestamp": "2024-01-01T00:00:00Z", "value": 23.5 },
{ "timestamp": "2024-01-01T01:00:00Z", "value": 24.1 }
]
}
Nested Arrays
Arrays within arrays:
{
"matrix": [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
}
Access nested elements:
data.matrix[0][0] // 1
data.matrix[1][2] // 6
Arrays vs Objects
Use arrays when:
- Order matters
- Items are similar/homogeneous
- You'll iterate over all items
- You need a list or collection
Use objects when:
- Order doesn't matter
- Each key has unique meaning
- You access items by name
- Structure is heterogeneous
Example - array is better:
// Good - homogeneous list
{ "colors": ["red", "blue", "green"] }
// Bad - should be array
{
"color1": "red",
"color2": "blue",
"color3": "green"
}
Empty Arrays
{ "items": [] }
Empty arrays are valid and often used to represent "no data".
Array Length
In JavaScript:
const data = { "items": [1, 2, 3, 4, 5] };
console.log(data.items.length); // 5
Iterating Arrays
const data = {
"users": [
{ "name": "Alice" },
{ "name": "Bob" }
]
};
data.users.forEach(user => {
console.log(user.name);
});
// Or with map
const names = data.users.map(user => user.name);
// ["Alice", "Bob"]
API Response Patterns
Wrapping array in object:
// Better
{
"users": [...],
"total": 100
}
// Avoid - harder to extend
[...]
Objects allow adding metadata (pagination, totals, errors) without breaking structure.
Envelope pattern:
{
"success": true,
"data": [...],
"error": null
}
Searching Arrays
const data = {
"users": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]
};
const user = data.users.find(u => u.id === 2);
console.log(user.name); // "Bob"
Filtering Arrays
const activeUsers = data.users.filter(u => u.active);
Sorting Considerations
JSON arrays maintain order, but objects don't:
// Order preserved
{ "items": [3, 1, 2] }
// Order not guaranteed
{ "3": "c", "1": "a", "2": "b" }
Large Arrays
For large datasets, consider pagination:
{
"data": [...], // Current page items
"pagination": {
"page": 1,
"pageSize": 50,
"totalPages": 20,
"totalItems": 1000
}
}
Array Validation
Check if value is array:
if (Array.isArray(data.items)) {
console.log("It's an array");
}
Common Mistakes
Trailing comma:
// Invalid
{ "items": [1, 2, 3,] }
Using array indices as meaningful keys:
// Bad - fragile, order-dependent
{
"0": "first",
"1": "second"
}
// Good
["first", "second"]
Transforming Data
const response = {
"users": [
{ "firstName": "Alice", "lastName": "Smith" },
{ "firstName": "Bob", "lastName": "Jones" }
]
};
const fullNames = response.users.map(u => `${u.firstName} ${u.lastName}`);
// ["Alice Smith", "Bob Jones"]
Flattening Nested Arrays
const data = {
"groups": [
{ "users": ["Alice", "Bob"] },
{ "users": ["Charlie", "David"] }
]
};
const allUsers = data.groups.flatMap(g => g.users);
// ["Alice", "Bob", "Charlie", "David"]
Real-World Example
{
"products": [
{
"id": "p1",
"name": "Laptop",
"price": 999.99,
"inStock": true,
"tags": ["electronics", "computers"],
"reviews": [
{ "rating": 5, "comment": "Great!" },
{ "rating": 4, "comment": "Good" }
]
},
{
"id": "p2",
"name": "Mouse",
"price": 29.99,
"inStock": false,
"tags": ["electronics", "accessories"],
"reviews": []
}
],
"totalProducts": 2,
"lastUpdated": "2024-01-15T10:00:00Z"
}
Further Reading
The JSON specification defines array syntax.
MDN's Array documentation covers JavaScript array methods.
Google's JSON style guide recommends array usage patterns.
JSON arrays are fundamental to representing collections of data.
0 comments