Lecture Notes Of Day 27: JavaScript with JSON

Rashmi Mishra
0

Lecture Notes Of Day 27

 JavaScript with JSON

Objective:

The goal of this lesson is to understand how to work with JSON (JavaScript Object Notation) data in JavaScript. We will learn how to fetch JSON data from external sources, parse it into JavaScript objects, and work with it effectively in our projects.


Topics Covered:

1.Fetching and Parsing JSON Data

2.Working with JSON Data in JavaScript Objects


1. Fetching and Parsing JSON Data

1.1 What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is primarily used for transmitting data between a server and a web application as a text. JSON represents data as key-value pairs.

Example of JSON:

{

  "name": "John Doe",

  "age": 30,

  "city": "New York"

}

1.2 Fetching JSON Data

To work with JSON in JavaScript, we first need to fetch it from a server or an external resource. The most common method for fetching data is using the fetch() function, which returns a promise.

Example:

fetch('https://api.example.com/data.json')

  .then(response => response.json())  // Parse the JSON response

  .then(data => {

    console.log(data);

  })

  .catch(error => {

    console.log('Error fetching data:', error);

  });

  • fetch(url): Initiates a request to the provided URL and returns a Promise.
  • .json(): Parses the JSON response into a JavaScript object.

1.3 Example: Fetching JSON from an API

Let's say we want to fetch JSON data from a public API. Here's an example of how to do it:

fetch('https://jsonplaceholder.typicode.com/users')

  .then(response => response.json())

  .then(data => {

    // Looping through the data to log each user's name

    data.forEach(user => {

      console.log(user.name);

    });

  })

  .catch(error => {

    console.log('Error:', error);

  });

This fetches a list of users in JSON format from the JSONPlaceholder API and logs the name of each user to the console.

1.4 Parsing JSON Data

When we receive JSON data as a string (such as from an API), we need to parse it into a JavaScript object before using it. This is done using JSON.parse().

Example:

let jsonString = '{"name": "Alice", "age": 25}';

let jsonObject = JSON.parse(jsonString);

console.log(jsonObject.name); // Output: Alice

console.log(jsonObject.age);  // Output: 25

  • JSON.parse(): Converts a JSON string into a JavaScript object.

2. Working with JSON Data in JavaScript Objects

Once we've fetched and parsed the JSON data into a JavaScript object, we can work with it just like any other JavaScript object. We can access properties, update values, and loop through arrays.

2.1 Accessing Data from a JSON Object

After parsing JSON data, we can access the values of the object using dot notation or bracket notation.

Example:

let person = {

  "name": "John Doe",

  "age": 30,

  "city": "New York"

};

// Accessing data using dot notation

console.log(person.name); // Output: John Doe

// Accessing data using bracket notation

console.log(person["age"]); // Output: 30

2.2 Updating Data in JSON Objects

Once you have a JavaScript object, you can update its properties.

Example:

let person = {

  "name": "John Doe",

  "age": 30,

  "city": "New York"

};

 

// Updating data

person.age = 31;

person.city = "Los Angeles";

 

// Output the updated object

console.log(person);

Output:

{

  "name": "John Doe",

  "age": 31,

  "city": "Los Angeles"

}

2.3 Working with Arrays in JSON

JSON can also contain arrays. You can loop through these arrays and manipulate the data inside them.

Example:

let jsonArray = [

  { "id": 1, "name": "Alice" },

  { "id": 2, "name": "Bob" },

  { "id": 3, "name": "Charlie" }

];

 

// Loop through the array and log each user's name

jsonArray.forEach(item => {

  console.log(item.name);

});

2.4 Example: Parsing and Using JSON Data

Here’s an example that combines parsing JSON, accessing the data, and manipulating it:

let jsonResponse = `{

  "employees": [

    {"name": "Alice", "role": "Developer"},

    {"name": "Bob", "role": "Designer"},

    {"name": "Charlie", "role": "Manager"}

  ]

}`;

 

let parsedData = JSON.parse(jsonResponse);

 

// Accessing and updating data

parsedData.employees.forEach(employee => {

  console.log(`${employee.name} is a ${employee.role}`);

});

 

// Adding a new employee

parsedData.employees.push({ "name": "Dave", "role": "QA Engineer" });

 

// Display updated employee list

console.log(parsedData.employees);


Output:

Alice is a Developer

Bob is a Designer

Charlie is a Manager


Summary

  • JSON (JavaScript Object Notation) is a format for representing data that is easy for humans to read and write, and easy for machines to parse and generate.
  • Fetching JSON: Use fetch() to retrieve JSON data from external resources.
  • Parsing JSON: Use JSON.parse() to convert a JSON string into a JavaScript object.
  • Working with JSON: Once parsed into a JavaScript object, you can easily manipulate the data (e.g., access, update, loop through).

By understanding how to work with JSON, you can handle data in your web applications, interact with APIs, and manage structured data effectively.


Practice:

1.Exercise: Fetch JSON data from a public API like JSONPlaceholder and display the names of all users on the webpage.

2.Exercise: Create a JSON object for a shopping cart. The object should contain an array of items, each with a name, price, and quantity. Write a function to calculate the total cost of the cart.


Additional Resources:

These resources will help you deepen your understanding of JSON and how to handle data in JavaScript effectively.

Post a Comment

0Comments

Post a Comment (0)