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:
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:
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);
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 }
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]}`); } }
Object.entries()
: A more modern and concise approach:Object.entries(response).forEach(([key, value]) => { console.log(`${key}: ${value}`); });
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}`); }); })();
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`); }); })();
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!