An array in JSON is an ordered list of values surrounded by square brackets []. Arrays are perfect for storing collections of similar data, like a list of usernames, a set of results, or a gallery of image URLs.
Hover over the array elements to see how they are indexed in a JSON collection:
Arrays in JSON can contain strings, numbers, objects, booleans, null, or even other arrays. Every item is separated by a comma.
{ "cars": ["Ford", "BMW", "Fiat"] }
You can access array values by using an index number. Remember: JSON arrays (and JavaScript arrays) are zero-based, meaning the first item is at index `0`.
let myObj = { "cars": ["Ford", "BMW", "Fiat"] };
// Access the first car
let x = myObj.cars[0]; // "Ford"
// Access the second car
let y = myObj.cars[1]; // "BMW"
Arrays are frequently found as values inside JSON objects. This allows you to combine structured data with simple lists.
{
"user": "Hridoy",
"hobbies": ["Coding", "Gaming", "Exploring"],
"projects": 15
}
Once you parse a JSON string into a JavaScript object, you can use any standard loop to iterate through the array items.
for (let i = 0; i < myObj.cars.length; i++) {
console.log(myObj.cars[i]);
}
// Or using for-in (returns indices)
for (let i in myObj.cars) {
x += myObj.cars[i];
}
Values in an array can also be arrays. This is common for matrices or complex data categorization.
const myData = {
"name": "John",
"skills": [
["HTML", "CSS"],
["JS", "JSON"]
]
};
// Access "JSON"
console.log(myData.skills[1][1]);
You can use the index to update any value in a parsed JSON array.
myObj.cars[0] = "Tesla";
delete to remove array items, it will leave an undefined hole in the array. For JSON data, it is usually better to use methods like splice().
[].[n] to retrieve items.length property tells you how many items are in the array.