Introduction
JSON (JavaScript Object Notation) is one of the most widely used data formats for transmitting structured information between systems. Among its core building blocks is the array, which allows you to represent ordered lists of data such as strings, numbers, objects, or even other arrays.
Whether you’re defining configuration files, sending data to an API, or processing server responses, understanding how to use arrays in JSON is essential. This guide covers how arrays work, how to define them, access them in code, and handle more complex cases like arrays of objects.
What Is an Array in JSON?
A JSON array is an ordered list enclosed in square brackets []. It can hold any combination of values, including:
- Strings
- Numbers
- Booleans
- Objects
- Other arrays
- null
Example: Array of strings
{
"colors": ["red", "green", "blue"]
}
JSON Array of Objects
One of the most powerful patterns in JSON is the array of objects. This is used to represent collections of structured data—like lists of users, products, or orders.
Example: Array of Objects
{
"users": [
{ "id": 1, "name": "Alice", "email": "alice@example.com" },
{ "id": 2, "name": "Bob", "email": "bob@example.com" }
]
}
JSON Array of Arrays
A JSON array of arrays is a nested data structure where each item inside the outer array is itself an array. This structure is often used to represent tabular data, matrices, or coordinate sets, where each inner array holds a related group of values
Example: Matrix (2D Grid)
{
"matrix": [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
}
Example: Coordinates
{
"coordinates": [
[35.6895, 139.6917], // Tokyo
[34.0522, -118.2437], // Los Angeles
[51.5074, -0.1278] // London
]
}
How to Manipulate JSON Arrays in Popular Languages?
Once you’ve parsed a JSON string into a native data structure, you can easily loop, filter, map, or modify arrays using the language’s built-in tools.
Below are examples in some of the most popular languages:
1. Manipulate JSON Arrays in JavaScript/TypeScript
JSON arrays are widely used in JavaScript and TypeScript to handle structured data — especially when working with API responses, local storage, databases, or dynamic UI rendering. Understanding how to manipulate them effectively is key to writing clean, efficient code.
Here are some common operations you’ll often need when working with JSON arrays:
// Sample JSON array of objects
const users = [
{ name: "Alice", active: true },
{ name: "Bob", active: false },
{ name: "Carol", active: true }
];
// 1. Loop through the array
users.forEach(user => {
console.log("User name:", user.name);
});
// 2. Filter items
const activeUsers = users.filter(user => user.active);
console.log("Active users:", activeUsers);
// 3. Sort by name
const sortedUsers = [...users].sort((a, b) => a.name.localeCompare(b.name));
console.log("Sorted users:", sortedUsers);
// 4. Add a new item
users.push({ name: "Dave", active: true });
console.log("After adding Dave:", users);
// 5. Remove an item by index (e.g., remove second user)
users.splice(1, 1);
console.log("After removing second user:", users);
// 6. Find a user by name
const foundUser = users.find(user => user.name === "Alice");
console.log("Found user:", foundUser);
// 7. Update an object in the array (e.g., set Bob to active if he exists)
const updatedUsers = users.map(user =>
user.name === "Bob" ? { ...user, active: true } : user
);
console.log("Updated users:", updatedUsers);
// 8. Convert array to JSON string
const jsonString = JSON.stringify(users);
console.log("JSON string:", jsonString);
// 9. Parse JSON string back to array
const parsedUsers = JSON.parse(jsonString);
console.log("Parsed users:", parsedUsers);
2. Manipulate JSON Arrays in Python
In Python, JSON arrays are typically represented as lists, and JSON objects as dictionaries. Python’s built-in json module makes it easy to work with JSON data — whether you’re consuming API responses, reading configuration files, or preparing structured data for export.
Using lists of dictionaries (i.e., JSON arrays of objects) is a common pattern when handling data in Python. This structure is both flexible and powerful, allowing you to perform operations like filtering, sorting, updating, and serializing easily with native Python features such as list comprehensions, sorted(), and dictionary unpacking.
import json
# Sample JSON array of objects (Python list of dicts)
users = [
{ "name": "Alice", "active": True },
{ "name": "Bob", "active": False },
{ "name": "Carol", "active": True }
]
# 1. Loop through the array
for user in users:
print("User name:", user["name"])
# 2. Filter items
active_users = [user for user in users if user["active"]]
print("Active users:", active_users)
# 3. Sort by name
sorted_users = sorted(users, key=lambda user: user["name"])
print("Sorted users:", sorted_users)
# 4. Add a new item
users.append({ "name": "Dave", "active": True })
print("After adding Dave:", users)
# 5. Remove an item by index (e.g., remove second user)
users.pop(1)
print("After removing second user:", users)
# 6. Find a user by name
found_user = next((user for user in users if user["name"] == "Alice"), None)
print("Found user:", found_user)
# 7. Update an object in the array (e.g., set Bob to active if he exists)
updated_users = [
{ **user, "active": True } if user["name"] == "Bob" else user
for user in users
]
print("Updated users:", updated_users)
# 8. Convert array to JSON string
json_string = json.dumps(users)
print("JSON string:", json_string)
# 9. Parse JSON string back to array
parsed_users = json.loads(json_string)
print("Parsed users:", parsed_users)
3. Manipulate JSON Arrays in Java
In Java, JSON arrays are commonly represented using List<Map<String, Object>> when working with libraries like Jackson, Gson, or org.json. These libraries allow you to parse, generate, and manipulate JSON data with ease.
Manipulating JSON arrays in Java is essential when dealing with REST API responses, data storage, or configuration files. Since Java is a statically typed language, you’ll often need to map JSON data to POJOs (Plain Old Java Objects), or use flexible types like List and Map when the structure is dynamic.
Example (Using Jackson)
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.*;
import java.util.stream.Collectors;
public class JsonArrayExample {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
// Sample JSON string
String json = "[{\"name\":\"Alice\",\"active\":true},{\"name\":\"Bob\",\"active\":false},{\"name\":\"Carol\",\"active\":true}]";
// 1. Parse JSON string into List of Map
List<Map<String, Object>> users = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>() {});
System.out.println("Original users: " + users);
// 2. Loop through array
for (Map<String, Object> user : users) {
System.out.println("User name: " + user.get("name"));
}
// 3. Filter active users
List<Map<String, Object>> activeUsers = users.stream()
.filter(user -> Boolean.TRUE.equals(user.get("active")))
.collect(Collectors.toList());
System.out.println("Active users: " + activeUsers);
// 4. Sort by name
users.sort(Comparator.comparing(user -> (String) user.get("name")));
System.out.println("Sorted users: " + users);
// 5. Add a new user
Map<String, Object> newUser = new HashMap<>();
newUser.put("name", "Dave");
newUser.put("active", true);
users.add(newUser);
System.out.println("After adding Dave: " + users);
// 6. Remove a user by index
users.remove(1);
System.out.println("After removing second user: " + users);
// 7. Find a user by name
Map<String, Object> found = users.stream()
.filter(user -> "Alice".equals(user.get("name")))
.findFirst()
.orElse(null);
System.out.println("Found user: " + found);
// 8. Update Bob to active (if exists)
for (Map<String, Object> user : users) {
if ("Bob".equals(user.get("name"))) {
user.put("active", true);
}
}
// 9. Convert list back to JSON string
String updatedJson = mapper.writeValueAsString(users);
System.out.println("Updated JSON string: " + updatedJson);
}
}
4. Manipulate JSON Arrays in PHP
In PHP, JSON arrays are typically decoded into associative arrays (for JSON objects) or indexed arrays (for JSON lists). PHP provides built-in functions like json_decode() and json_encode() to parse and serialize JSON data, making it easy to manipulate JSON structures directly.
Working with arrays of objects (i.e., a JSON array of associative arrays) is a common pattern when handling API responses, configuration files, or AJAX calls. PHP’s flexible array structure makes it very convenient to perform operations like filtering, sorting, updating, and serializing JSON arrays.
<?php
// Sample JSON string
$json = '[{"name":"Alice","active":true},{"name":"Bob","active":false},{"name":"Carol","active":true}]';
// 1. Decode JSON string to PHP array
$users = json_decode($json, true);
echo "Original users:\n";
print_r($users);
// 2. Loop through the array
foreach ($users as $user) {
echo "User name: " . $user['name'] . "\n";
}
// 3. Filter active users
$activeUsers = array_filter($users, function ($user) {
return $user['active'] === true;
});
echo "Active users:\n";
print_r($activeUsers);
// 4. Sort users by name
usort($users, function ($a, $b) {
return strcmp($a['name'], $b['name']);
});
echo "Sorted users:\n";
print_r($users);
// 5. Add a new user
$users[] = ["name" => "Dave", "active" => true];
echo "After adding Dave:\n";
print_r($users);
// 6. Remove a user by index (e.g., remove second user)
array_splice($users, 1, 1);
echo "After removing second user:\n";
print_r($users);
// 7. Find a user by name
$foundUser = null;
foreach ($users as $user) {
if ($user['name'] === 'Alice') {
$foundUser = $user;
break;
}
}
echo "Found user:\n";
print_r($foundUser);
// 8. Update Bob to active if exists
foreach ($users as &$user) {
if ($user['name'] === 'Bob') {
$user['active'] = true;
}
}
unset($user); // break reference
// 9. Encode back to JSON
$updatedJson = json_encode($users, JSON_PRETTY_PRINT);
echo "Updated JSON:\n";
echo $updatedJson;
5. Manipulate JSON Arrays in Ruby
In Ruby, JSON arrays are typically parsed into arrays of hashes using the built-in json library. This structure is ideal for working with API responses, configuration files, and any structured data exchange. Ruby’s expressive syntax and enumerable methods (each, select, sort_by, map, etc.) make it very convenient to manipulate JSON arrays.
require 'json'
# Sample JSON string
json = '[{"name":"Alice","active":true},{"name":"Bob","active":false},{"name":"Carol","active":true}]'
# 1. Parse JSON string into Ruby array of hashes
users = JSON.parse(json)
puts "Original users:"
puts users
# 2. Loop through the array
users.each do |user|
puts "User name: #{user['name']}"
end
# 3. Filter active users
active_users = users.select { |user| user['active'] }
puts "Active users:"
puts active_users
# 4. Sort users by name
sorted_users = users.sort_by { |user| user['name'] }
puts "Sorted users:"
puts sorted_users
# 5. Add a new user
users << { 'name' => 'Dave', 'active' => true }
puts "After adding Dave:"
puts users
# 6. Remove a user by index (e.g., remove second user)
users.delete_at(1)
puts "After removing second user:"
puts users
# 7. Find a user by name
found_user = users.find { |user| user['name'] == 'Alice' }
puts "Found user:"
puts found_user
# 8. Update Bob to active (if exists)
users.map! do |user|
user['name'] == 'Bob' ? user.merge('active' => true) : user
end
# 9. Convert back to JSON string
updated_json = JSON.pretty_generate(users)
puts "Updated JSON string:"
puts updated_json
6. Manipulate JSON Arrays in Golang
In Go, JSON arrays are typically decoded into slices of structs or []map[string]interface{} for dynamic structures. The encoding/json package provides powerful and flexible tools to encode/decode JSON. JSON manipulation is common in Go when dealing with REST APIs, configuration files, or data transformation.
Go’s strict typing and performance make it ideal for robust JSON handling, especially when defining custom types for structured data. Below is a complete example demonstrating how to manipulate JSON arrays in Go, covering parsing, looping, filtering, sorting, updating, and converting back to JSON.
package main
import (
"encoding/json"
"fmt"
"sort"
)
type User struct {
Name string `json:"name"`
Active bool `json:"active"`
}
func main() {
// Sample JSON array
jsonStr := `[{"name":"Alice","active":true},{"name":"Bob","active":false},{"name":"Carol","active":true}]`
// 1. Parse JSON string to slice of structs
var users []User
err := json.Unmarshal([]byte(jsonStr), &users)
if err != nil {
panic(err)
}
fmt.Println("Original users:", users)
// 2. Loop through the array
for _, user := range users {
fmt.Println("User name:", user.Name)
}
// 3. Filter active users
var activeUsers []User
for _, user := range users {
if user.Active {
activeUsers = append(activeUsers, user)
}
}
fmt.Println("Active users:", activeUsers)
// 4. Sort users by name
sort.Slice(users, func(i, j int) bool {
return users[i].Name < users[j].Name
})
fmt.Println("Sorted users:", users)
// 5. Add a new user
users = append(users, User{Name: "Dave", Active: true})
fmt.Println("After adding Dave:", users)
// 6. Remove user by index (e.g., remove second user)
if len(users) > 1 {
users = append(users[:1], users[2:]...)
}
fmt.Println("After removing second user:", users)
// 7. Find user by name
var found *User
for i := range users {
if users[i].Name == "Alice" {
found = &users[i]
break
}
}
fmt.Println("Found user:", found)
// 8. Update Bob to active if exists
for i := range users {
if users[i].Name == "Bob" {
users[i].Active = true
}
}
// 9. Convert slice back to JSON
updatedJSON, err := json.MarshalIndent(users, "", " ")
if err != nil {
panic(err)
}
fmt.Println("Updated JSON:")
fmt.Println(string(updatedJSON))
}
Useful Online Tools for Working with JSON Arrays
1. CodeUtility: JSON Viewer/Beautifier
- Auto-format with line numbers.
- Toggle between compact and pretty view.
- Built-in validation.
Link: https://beautifyjson.codeutility.io
2. CodeUtility: JSON to Yaml
- Convert JSON array to YAML.
- Filter or extract array fields.
Link: https://json2yaml.codeutility.io
3. JSONLint: JSON Validator
- Validate and format JSON.
- Checks if your JSON array is syntactically correct.
- Auto-indents and highlights errors.
Link: https://jsonlint.com