Connect with us

Technology

Fast Tip: Loop By means of a JSON Response in JavaScript – SitePoint


When fetching information from a distant server, the server’s response will typically be in JSON format. On this fast tip, I’ll display how you should utilize JavaScript to parse the server’s response, in order to entry the info you require.

This course of will usually encompass two steps: decoding the info to a local construction (reminiscent of an array or an object), then utilizing considered one of JavaScript’s in-built strategies to loop via that information construction. On this article, I’ll cowl each steps, utilizing loads of runnable examples.

What’s JSON?

Earlier than we take a look at easy methods to take care of JSON, let’s take a second to grasp what it’s (and what it isn’t).

JSON stands for JavaScript Object Notation. It’s a language-independent, text-based format, which is often used for transmitting information in net purposes. JSON was impressed by the JavaScript Object Literal notation, however there are variations between the 2. For instance, in JSON keys should be quoted utilizing double quotes, whereas in object literals this isn’t the case.

There are two methods information might be saved in JSON:

  • a set of title/worth pairs (aka a JSON object)
  • an ordered record of values (aka a JSON array)

When receiving information from an internet server, the info is all the time a string, which implies that it’s your job to transform it into a knowledge construction you possibly can work with.

In the event you’d like to seek out out extra about how JSON works, please go to the JSON web site.

Fetching JSON from a Distant API

Within the following examples, we’ll use the implausible icanhazdadjoke API. As you possibly can learn in its documentation, making a GET request the place the Settle for header is about to software/json will see the API return a JSON payload.

Let’s begin with a easy instance:

const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    console.log(typeof xhr.responseText);
    console.log(xhr.responseText);
  }
};
xhr.open('GET', 'https://icanhazdadjoke.com/', true);
xhr.setRequestHeader('Settle for', 'software/json');
xhr.ship(null);



As we are able to see, the server returned us a string. We’ll have to parse this right into a JavaScript object earlier than we are able to loop via its properties. We are able to do that with JSON.parse():

if (xhr.readyState === XMLHttpRequest.DONE) {
  const res = JSON.parse(xhr.responseText);
  console.log(res);
};


As soon as we’ve got our response as a JavaScript object, there are a variety of strategies we are able to use to loop via it.

Use a for...in Loop

A for…in loop iterates over all enumerable properties of an object:

const res = JSON.parse(xhr.responseText);

for (const key in res){
  if(obj.hasOwnProperty(key)){
    console.log(`${key} : ${res[key]}`)
  }
}




Please bear in mind that for...of loops will iterate over the whole prototype chain, so right here we’re utilizing hasOwnProperty to make sure that the property belongs to our res object.

Use Object.entries, Object.values or Object.entries

An alternate strategy to above is to make use of considered one of Object.keys(), Object.values() or Object.entries(). These will return an array which we are able to then iterate over.

Let’s check out utilizing Object.entries. This returns an array of the important thing/worth pairs of the item we cross it:

const res = JSON.parse(xhr.responseText);

Object.entries(res).forEach((entry) => {
  const [key, value] = entry;
  console.log(`${key}: ${worth}`);
});




Word that the const [key, value] = entry; syntax is an instance of array destructuring that was launched to the language in ES2015.

That is far more concise, avoids the aforementioned prototype downside, and is my most popular technique of looping via a JSON response.

Utilizing the Fetch API

Whereas the tactic above utilizing the XMLHttpRequest object works simply effective, it will probably get unwieldy fairly rapidly. We are able to do higher.

The Fetch API is a Promise-based API, which allows a cleaner, extra concise syntax and helps preserve you out of callback hell. It gives a fetch() technique outlined on the window object, which you should utilize to carry out requests. This technique returns a Promise that you should utilize to retrieve the response of the request.

Let’s rewrite our earlier instance to make use of it:

(async () => {
  const res = await fetch('https://icanhazdadjoke.com/', {
    headers: { Settle for: 'software/json' },
  });
  const json = await res.json();
  Object.entries(json).forEach(([key, value]) => {
    console.log(`${key}: ${worth}`);
  });
})();




The Fetch API returns a response stream. This isn’t JSON, so as a substitute of making an attempt to name JSON.parse() on it, we’ll want to make use of its response.json() perform. This returns a Promise that resolves with the results of parsing the response’s physique textual content as JSON.

Coping with an Array

As talked about on the prime of the article, an ordered record of values (aka an array), is legitimate JSON, so earlier than we end, let’s study easy methods to take care of such a response.

For the ultimate instance, we’ll use GitHub’s REST API to get an inventory of a person’s repositories:

(async () => {
  async perform getRepos(username) {
    const url = `https://api.github.com/customers/${username}/repos`;

    const response = await fetch(url);
    const repositories = await response.json();

    return repositories;
  }

  const repos = await getRepos('jameshibbard');
  console.log(repos);
})();


As you possibly can see, the API has returned an array of objects. To entry every of the person objects, we are able to use an everyday forEach technique:

repos.forEach((repo) => {
  console.log(`{$repo.title} has ${repo.stargazers_count} stars`);
});






Alternatively, you possibly can in fact use any of the strategies mentioned above to loop via the entire object’s properties and log them to the console:

repos.forEach((repo) => {
  Object.entries(repo).forEach(([key, value]) => {
    console.log(`${key}: ${worth}`);
  });
});





Conclusion

On this fast tip, we’ve checked out what JSON is. I’ve demonstrated easy methods to parse a JSON response from a server right into a native information construction (reminiscent of an array or an object), and easy methods to loop via such a construction, in order to entry the info it comprises.

In the event you’re having bother with something offered on this article, why not cease by SitePoint’s Boards, the place there are many pleasant individuals that will help you out.

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *