Home > Web Front-end > JS Tutorial > How to Loop Through a JSON Response in JavaScript

How to Loop Through a JSON Response in JavaScript

Jennifer Aniston
Release: 2025-02-10 12:05:10
Original
775 people have browsed it

How to Loop Through a JSON Response in JavaScript

This tutorial demonstrates how to efficiently parse JSON data received from a remote server using JavaScript. We'll cover the process in two steps: decoding the JSON string into a usable JavaScript structure (object or array), and then iterating through that structure to access the data. We'll use practical examples with both XMLHttpRequest and the more modern fetch API.

Key Concepts:

  1. JSON (JavaScript Object Notation): A lightweight, text-based data-interchange format widely used in web applications. While inspired by JavaScript object literal syntax, JSON strictly requires double quotes around keys.
  2. JSON Parsing: The process of converting a JSON string into a JavaScript object or array. This is crucial because the server sends data as a string, which needs to be parsed before it can be used.
  3. Iteration: After parsing, we use JavaScript's built-in methods like for...in, Object.entries, Object.values, or array methods (forEach, etc.) to access individual data elements within the parsed structure.

Understanding JSON:

JSON data can be structured in two ways:

  • JSON Object: A collection of name/value pairs (similar to a JavaScript object).
  • JSON Array: An ordered list of values (similar to a JavaScript array).

Fetching JSON with XMLHttpRequest:

Let's use the icanhazdadjoke API (a simple joke API) as an example. This API returns JSON data when the Accept header is set to application/json.

First, we fetch the data:

const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    console.log(typeof xhr.responseText); // Output: string
    console.log(xhr.responseText);       // Output: JSON string
  }
};
xhr.open('GET', 'https://icanhazdadjoke.com/', true);
xhr.setRequestHeader('Accept', 'application/json');
xhr.send(null);
Copy after login

The response is a string. We parse it using JSON.parse():

if (xhr.readyState === XMLHttpRequest.DONE) {
  const response = JSON.parse(xhr.responseText);
  console.log(response); // Output: Parsed JavaScript object
}
Copy after login

Now, we can iterate through the object's properties. Here are a few ways:

  • for...in loop:
for (const key in response) {
  if (response.hasOwnProperty(key)) {
    console.log(`${key}: ${response[key]}`);
  }
}
Copy after login
  • Object.entries(): A more modern and concise approach:
Object.entries(response).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});
Copy after login

Fetching JSON with the fetch API:

The fetch API offers a cleaner, promise-based approach:

(async () => {
  const response = await fetch('https://icanhazdadjoke.com/', {
    headers: { Accept: 'application/json' },
  });
  const jsonData = await response.json();
  Object.entries(jsonData).forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
  });
})();
Copy after login

response.json() parses the response body as JSON and returns a promise that resolves with the parsed data.

Handling JSON Arrays:

Let's fetch a list of repositories from the GitHub API:

(async () => {
  const repos = await fetch('https://api.github.com/users/jameshibbard/repos').then(res => res.json());
  repos.forEach(repo => {
    console.log(`${repo.name} has ${repo.stargazers_count} stars`);
  });
})();
Copy after login

This example demonstrates iterating through a JSON array using forEach. You can use other array methods like map or filter for more complex operations.

Conclusion:

This tutorial covered the essential steps of parsing and iterating through JSON responses in JavaScript, using both XMLHttpRequest and the fetch API. Remember to handle potential errors (e.g., network issues, invalid JSON) in a production environment. The fetch API, with its promise-based approach, is generally preferred for its cleaner syntax and better error handling capabilities.

The above is the detailed content of How to Loop Through a JSON Response in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template