web123456

How to loop through JSON response in JavaScript

When fetching data from a remote server, the server's response is usually in JSON format. In this article, I will demonstrate how to use itJavaScriptResolve the server's response to access the required data. This process usually consists of two steps: decoding the data into a native structure (e.g.Arrayor object), then iterate through the data structure using JavaScript's built-in methods.

1. What is JSON?

JSON (JavaScript Object Notation, JS object tag)It is a lightweight data exchange format. It is basedECMAScript(a subset of JS specifications formulated by w3c) uses a text format that is completely independent of the programming language to store and represent data. The concise and clear hierarchy makes JSON an ideal data exchange language. Easy to read and write by people, but also easy to analyze and generate by machines, and effectively improve network transmission efficiency. (voiceover: The father of JSON is calledDouglas CrockfordAlthough he is not that likable in the community, he cannot deny that he is rightJavaScriptContributions made, famous open source projectsJSlintHe also wrote it, and he also published a book calledHow JavaScript Works, Chinese translation of "JavaScript Language Essence")

Data can be stored in JSON in two ways:

  1. Collection of name/value pairs (aka JSON object)
  2. Ordered list of values ​​(also known as JSON array)

When receiving data from a web server, the data is always a string, which means converting it to a data structure that can be used is a necessary job, if you want to learn more about how JSON works

2. Obtain the interface from the remote API

1. UseXMLHttpRequest API

const xhr = new XMLHttpRequest();
 = () => {
    if ( === ) {
        (typeof );
        ();
    }
};
('GET', '', true);
('Accept', 'application/json');
(null);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

The returned data is:

// string
// {"id":"helloworld","joke":"today is Friday!","status":200}
  • 1
  • 2

The server returns a string. We need to parse it into a JavaScript object before we can traverse its properties. We can use()Doing this, as shown below:

if ( === ) {
    const res = ();
    (res);
};
//Object { id: "helloworld", joke: "today is Friday!", status: 200 }
  • 1
  • 2
  • 3
  • 4
  • 5

2. UseFetch API

Although the aboveXMLHttpRequestThe object method works well, but it becomes very clumsy in complex scenarios. Below we use the newly provided API of the browser, which is the method defined on the window objectfetch, you can use this method to execute the request. This method returns a Promise that can be used to retrieve the requested response.

(async () => {
    const res = await fetch('/', {
        headers: { Accept: 'application/json' },
    });
    const json = await ();
    (json).forEach(([key, value]) => {
        (`${key}: ${value}`);
    });
})();

// id : helloworld
// joke : today is Friday
// status : 200
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

Fetch APIReturns the response stream. This is not JSON, so() needs to try using it's()functionInstead of calling it. This returns a Promise that parses the body text of the response to the result of JSON.

3. Traverse data in various ways

1. Use for…in

const res = ();

for (const key in res){
    if((key)){
        (`${key} : ${res[key]}`)
    }
}

// id : helloworld
// joke : today is Friday
// status : 200
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

2. Use, or

const res = ();

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

// id : helloworld
// joke : today is Friday
// status : 200
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3. Processing arrays

Ordered lists of values ​​(also known as arrays) are also valid JSON, so let's look at how such responses are handled.

For this example, we will use GitHub'sREST APITo get a list of user repositories:

(async () => {
  async function getRepos(username) {
    const url = `/users/${username}/repos`;

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

    return repositories;
  }

  const repos = await getRepos('sylove');
  (repos);
})();

// Array(30) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

As you can see, the API returns an array of objects. To access each individual object, we can use the regular forEach method:

((repo) => {
  (`${} has ${repo.stargazers_count} stars`);
});

// CQ has 0 stars
// VM99:14 Food has 1 stars
// VM99:14 vue-blog-generater has 0 stars
// VM99:14 YouDe has 0 stars
// ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Also, you can of course use any of the methods discussed above to iterate through all the properties of the object and log them to the console:

((repo) => {
  (repo).forEach(([key, value]) => {
    (`${key}: ${value}`);
  });
});

// id: 187614270
// VM104:15 node_id: MDEwOlJlcG9zaXRvcnkxODc2MTQyNzA=
// VM104:15 name: CQ
// ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

in conclusion

In this article, we looked at what JSON is. I've demonstrated how to resolve the JSON response of the server to nativeData structure(such as an array or object), and how to iterate through this structure to access the data contained therein. Most of our interactions with servers revolve around this and this. I hope this article will be helpful to you.