HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JSON Arrays

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.


Array Visualizer

Hover over the array elements to see how they are indexed in a JSON collection:

[0] Ford
[1] BMW
[2] Fiat
[3] Audi
Hover over an item to see its access logic...

Array Syntax

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"] }

Accessing Array Values

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 in Objects

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
}

Looping Through an Array

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];
}

Nested Arrays in JSON

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]); 

Modifying Array Values

You can use the index to update any value in a parsed JSON array.

myObj.cars[0] = "Tesla";
Note: While you can use 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().

Key Points to Remember

  • Arrays are surrounded by [].
  • They are zero-indexed (start at 0).
  • They can contain any valid JSON data type.
  • Use index access [n] to retrieve items.
  • The length property tells you how many items are in the array.