🚀 Master JavaScript & Java with Ease!
Subscribe to Ram N Java for clean, beginner-friendly coding guides!
🔔 Subscribe to Ram N JavaIntroduction: Understanding JSON Arrays
Arrays are an essential part of JSON format. They allow you to hold ordered lists of items, such as strings, numbers, booleans, objects, or even other arrays.
In this guide, you will learn how JSON arrays are structured, how to write them, and how to access values inside them using standard JavaScript index notation.
1. How Does a JSON Array Look?
In JSON, arrays are written inside square brackets ([ ]). Each item is separated by a comma. An array can exist as a standalone list or as a value inside a JSON object:
let myData = {
"name": "Ram",
"age": 30,
"cars": ["Ford", "BMW", "Fiat"]
};
Here, cars is an array containing three car names.
2. Accessing Items by Index
JSON arrays are zero-indexed, meaning the first item begins at position 0, the second at 1, and so on.
// Accessing the first item let firstCar = myData.cars[0]; // "Ford" // Accessing the second item let secondCar = myData.cars[1]; // "BMW" console.log(firstCar); console.log(secondCar);
3. Reading All Items with a Loop
You can easily read through all items in an array using a simple for loop:
for (let i = 0; i < myData.cars.length; i++) {
console.log(myData.cars[i]);
}
// Output:
// Ford
// BMW
// Fiat
Key Takeaways
- Arrays are enclosed in square brackets
[ ]. - Indices start at
0. - Use
array.lengthto get the total count of items.
No comments:
Post a Comment