Arrays in JSON are incredibly powerful and resemble standard JavaScript arrays perfectly.
They are written entirely inside square brackets [] and contain comma-separated values.
The value assigned to a JSON object key can be a massive array.
This array can contain strings, numbers, booleans, or even other nested JSON objects!
This structural capability allows you to transmit massive lists of users or products easily.
Once the JSON string is parsed, you access array elements using their specific index number.
Remember, JavaScript arrays are universally zero-indexed, meaning the first element is always [0].
let jsonStr = '{"name":"John", "cars":["Ford", "BMW", "Fiat"]}';
// Parse the string into an object
let myObj = JSON.parse(jsonStr);
// Accessing the second car in the array
console.log(myObj.cars[1]); // Outputs: BMW
Just like standard JavaScript arrays, you can use a standard for loop to extract elements dynamically.
You can also use the modern for...of loop to traverse the parsed JSON array elegantly.
Building HTML lists from JSON arrays is a critical skill for all frontend developers!
In a parsed JSON array, how do you access the very first element?