Quick Tip: How to Loop Through a JSON Response in JavaScript


How to Loop Through a JSON Response in JavaScript

When fetching data from a remote server, the server’s response will often be in JSON format. In this quick tip, I’ll demonstrate how you can use JavaScript to parse the server’s response, so as to access the data you require.

This process will typically consist of two steps: decoding the data to a native structure (such as an array or an object), then using one of JavaScript’s in-built methods to loop through that data structure. In this article, I’ll cover both steps, using plenty of runnable examples.

What is JSON?

Before we look at how to deal with JSON, let’s take a second to understand what it is (and what it isn’t).

JSON stands for JavaScript Object Notation. It’s a language-independent, text-based format, which is commonly used for transmitting data in web applications. JSON was inspired by the JavaScript Object Literal notation, but there are differences between the two. For example, in JSON keys must be quoted using double quotes, while in object literals this is not the case.

There are two ways data can be stored in JSON:

  • a collection of name/value pairs (aka a JSON object)
  • an ordered list of values (aka a JSON array)

When receiving data from a web server, the data is always a string, which means that it’s your job to convert it into a data structure you can work with.

If you’d like to find out more about how JSON works, please visit the JSON website.

Fetching JSON from a Remote API

In the following examples, we’ll use the fantastic icanhazdadjoke API. As you can read in its documentation, making a GET request where the Accept header is set to application/json will see the API return a JSON payload.

Let’s start with a simple example:

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('Accept', 'application/json');
xhr.send(null);

// string
// {"id":"daaUfibh","joke":"Why was the big cat disqualified from the race? Because it was a cheetah.","status":200}

As we can see, the server returned us a string. We’ll need to parse this into a JavaScript object before we can loop through its properties. We can do this with JSON.parse():

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

// Object { id: "fiyPR7wPZDd", joke: "When does a joke become a dad joke? When it becomes apparent.", status: 200 }

Once we have our response as a JavaScript object, there are a number of methods we can use to loop through 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]}`)
  }
}

// id : H6Elb2LBdxc
// joke : What's blue and not very heavy?  Light blue.
// status : 200

Please be aware that for...of loops will iterate over the entire prototype chain, so here we’re using hasOwnProperty to ensure that the property belongs to our res object.

Continue reading
Quick Tip: How to Loop Through a JSON Response in JavaScript
on SitePoint.

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Quick Tip: How to Loop Through a JSON Response in JavaScript

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.