Conteúdo do curso
JavaScript Course for Beginners: Fundamentals and Practice
Sobre a Aula

JSON Data Manipulation

Welcome to the second class of Module 7! In this journey, you will become an expert in JSON, a lightweight and easy-to-exchange data format between systems. Explore how JSON facilitates communication between client and server in AJAX applications, enabling efficient and interactive data sending and receiving.

JSON Syntax

JSON (JavaScript Object Notation) is a data representation format widely used in web applications.

It is based on JavaScript syntax and is very similar to how we write objects and arrays in JavaScript.

Imagine JSON as a recipe book, where you have different ingredients with their respective quantities and preparation instructions.

Each recipe consists of a set of information organized in key-value pairs. Keys represent ingredient names, and values represent information associated with each ingredient.

The basic JSON syntax involves placing key-value pairs inside curly braces {} to represent an object or inside square brackets [] to represent an array.

Each key-value pair is separated by a comma.

For example, to represent a person with a name, age, and address, we would have the following JSON:

{
  "name": "João",
  "age": 30,
  "address": {
    "street": "Rua das Flores",
    "number": 123
  }
}

In this example, we have an object with three key-value pairs: “name” with the value “João”, “age” with the value 30, and “address” with a nested object containing the keys “street” and “number.”

JSON syntax is straightforward and readable, making it widely used for data transfer and storage.

It’s essential to remember that when working with JSON, key names and values must be in double quotes.

Parsing JSON

JSON parsing is the process of converting a JSON string into a JavaScript object. It’s like “translating” the information written in JSON so that we can easily manipulate it in our JavaScript code.

We can draw an analogy with translating a book. Suppose you have a book written in an unknown language, and you want to understand its content.

To achieve this, you hire a translator who reads the book and transforms the text into a language you understand.

Similarly, when we perform JSON parsing, we are “hiring” JavaScript to read the JSON string and transform it into an object that we can use in our code.

To parse JSON in JavaScript, we use the JSON.parse() method. This method takes the JSON string as an argument and returns an equivalent JavaScript object.

For example, if we have the following JSON string:

'{"name": "João", "age": 30}'

We can parse this string as follows:

const jsonString = '{"name": "João", "age": 30}';
const object = JSON.parse(jsonString);

After parsing, the object variable will contain a JavaScript object with properties “name” and “age,” which we can access normally.

JSON parsing is an important step when working with APIs or receiving data from a server in JSON format. It allows us to transform this data into JavaScript objects for easier and more efficient manipulation.

Accessing Properties

Accessing properties is the way to get or modify the values of a property of a JavaScript object. We can think of properties as the characteristics or information associated with an object.

Let’s use an analogy with a mailbox to understand the concept. Suppose you have a mailbox with several letters inside. Each letter has a sender, a recipient, and content.

In this context, the mailbox is the object, and the letters are the properties. To access a property, you need to know the name of the letter you want to read or modify, such as “sender” or “content.”

In JavaScript, to access a property of an object, we use the dot notation (.) or bracket notation ([]).

For example, if we have an object named letter with the property sender, we can access the value of this property as follows:

const letter = {
  sender: "João",
  recipient: "Maria",
  content: "Hello, how are you?"
};

console.log(letter.sender); // Output: "João"

We can also use bracket notation to access the property:

console.log(letter["sender"]); // Output: "João"

These access forms are equivalent and allow us to obtain the value of the desired property.

Additionally, we can modify the value of a property using the same principle. Simply assign a new value to the property:

letter.sender = "Carlos";
console.log(letter.sender); // Output: "Carlos"

In summary, accessing properties allows us to get and modify the values associated with a JavaScript object using dot notation (.) or bracket notation ([]).

It’s like opening the mailbox and reading or altering the contents of the letters inside.

Iterating Over Arrays and JSON Objects

Iterating over arrays and JSON objects is a technique used to traverse and work with the elements present in a list of values or a complex data structure.

We can draw an analogy with the idea of visiting different cities on a travel itinerary.

Imagine you have an itinerary with several cities to visit, each with its characteristics and attractions.

The itinerary can be represented by an array or a JSON object, where each element or property contains information about a specific city.

To go through all the cities on the itinerary, we can use a loop, such as for or forEach, allowing us to access each city one by one.

Thus, we can perform specific actions for each city, such as taking photos, trying local foods, or visiting tourist spots.

In the case of an array, the for loop is very useful. It allows us to iterate over each element of the array, executing a code block for each iteration.

We can use a counter to keep track of the current index and access the corresponding element.

In the example of the travel itinerary, we can use the for loop to go through each city and display its name:

const itinerary = ["Rio de Janeiro", "Paris", "New York", "Tokyo"];
for (let i = 0; i < itinerary.length; i++) {
  console.log(itinerary[i]); // Displays the name of each city
}

For a JSON object, we can use the for...in loop to traverse the object’s properties. It allows us to access each property and perform specific operations for each one.

Continuing with the travel itinerary example, if we have a JSON object with detailed information about each city, we can use for...in to display the details of each city:

const city1 = {
  name: "Rio de Janeiro",
  population: 6710000,
  touristSpots: ["Christ the Redeemer", "Sugarloaf Mountain", "Copacabana"]
};

for (let property in city1) {
  console.log(property + ": " + city1[property]); // Displays each property and its value
}

In summary, iterating over arrays and JSON objects allows us to traverse and work with the elements present in a list of values or a complex data structure.

It’s like following a travel itinerary, visiting each city and performing specific activities in each one.

We use loops, such as for or for...in, to access the elements or properties one by one and perform specific operations.

Stringify JSON

The Stringify JSON operation is used to convert

a JavaScript object into a JSON string. We can draw an analogy with wrapping a gift.

Imagine you have a JavaScript object that contains several properties and values, just like a gift that has different items inside.

To gift someone, you need to wrap the gift in wrapping paper, creating a visual representation of its contents.

Similarly, when using Stringify JSON, you are wrapping the JavaScript object in a JSON string, creating a textual representation of your data.

This is useful when you want to send data to a server or store it in a file, for example.

During the Stringify JSON process, the JavaScript object is converted into a formatted sequence of characters according to the JSON syntax.

The object’s properties become keys in the JSON string, and the corresponding values are converted into their respective JSON formats, such as strings, numbers, or booleans.

Let’s use an example to illustrate this:

const person = {
  name: "João",
  age: 25,
  profession: "Engineer"
};

const personJSON = JSON.stringify(person);
console.log(personJSON);

In this example, we have an object named person with different properties like name, age, and profession.

By applying JSON.stringify(person), the object is converted into a JSON string, which is stored in the personJSON variable.

If we display the value of personJSON, we will see the textual representation of the object in JSON format:

{"name":"João","age":25,"profession":"Engineer"}

Note that all properties are enclosed in double quotes, and the values are formatted according to the JSON syntax.

In summary, Stringify JSON is a process that transforms a JavaScript object into a JSON string.

It’s like wrapping a gift in wrapping paper, creating a textual representation of the data contained in the object.

This is useful for sending data to a server or storing it in a format that can be easily shared or persisted.

Error Handling

When working with JSON in JavaScript, it’s essential to consider error handling to deal with situations where JSON manipulation might fail.

I’ll briefly explain how we can approach error handling when dealing with JSON.

One of the most common situations is when we try to parse an invalid JSON string.

To handle this, we can use the JSON.parse() method, which converts a JSON string into a JavaScript object.

However, if the string is not in the correct format, an error will occur.

We can wrap the call to JSON.parse() in a try-catch block to catch this error.

If an exception occurs, the catch block will be executed, allowing us to handle the problem appropriately. For example:

try {
  const jsonString = '{"name": "João", "age": 25}'; // Valid JSON string
  const obj = JSON.parse(jsonString); // Parsing the JSON string
  console.log(obj);
} catch (error) {
  console.log("An error occurred while parsing the JSON:", error);
}

In this example, we have a valid JSON string converted to a JavaScript object using JSON.parse().

If an error occurs during parsing, the catch block will be triggered, and the error message will be displayed.

Another situation where we can apply error handling is when using the JSON.stringify() method, which converts a JavaScript object into a JSON string.

Errors can occur if the object contains non-serializable values, such as functions or circular references.

To handle these errors, we can again wrap the call to JSON.stringify() in a try-catch block and handle the error appropriately. Here’s an example:

try {
  const obj = { name: "Maria", age: 30, birthDate: new Date() }; // Object with non-serializable value
  const jsonString = JSON.stringify(obj); // Conversion to JSON string
  console.log(jsonString);
} catch (error) {
  console.log("An error occurred while converting the object to JSON:", error);
}

In this case, we have an object with a property birthDate containing a non-serializable value (a Date object). If we try to convert this object to a JSON string using JSON.stringify(), an error will occur.

The catch block will be triggered, allowing us to handle the error according to our needs.

In summary, error handling related to JSON in JavaScript involves using try-catch blocks when parsing an invalid JSON string with JSON.parse() and when converting objects to JSON strings with JSON.stringify().

This approach allows us to capture and handle errors appropriately, ensuring a more controlled and robust execution of our code.

Challenge

  • Create a web page that uses AJAX to fetch data from an external API that returns data in JSON format.
  • Analyze the JSON data and display it on the web page in an organized manner.

This approach allows us to capture and handle errors appropriately, ensuring a more controlled and robust execution of our code.

Now that you’ve learned about JSON syntax and manipulation, including parsing, property access, iteration, stringify, and error handling, we’re ready to take the next step in our knowledge.

Let’s explore the use of APIs to obtain external data.

Entrar na conversa
Rolar para cima