-->

JavaScript - JSON Part 4: Accessing JSON Data

How to Access JSON Data?

Once a JSON string is converted into an object, you can access values using dot notation (.) or bracket notation ([]).

Example 5: Accessing Nested JSON Data

const employee = {

    name: "David",

    department: {

        name: "IT",

        location: "New York"

    }

};

console.log(employee.name); // Output: David

console.log(employee.department.location); // Output: New York

Explanation:

employee.name accesses "David".

employee.department.location accesses "New York" (nested data).

Example 6: Accessing Data in JSON Arrays

JSON can store arrays:

const users = [

    { name: "Alice", age: 25 },

    { name: "Bob", age: 30 }

];

console.log(users[0].name); // Output: Alice

console.log(users[1].age); // Output: 30

JSON arrays store multiple objects.

Access using index (users[0], users[1]).