Categories
JavaScript Answers

How to parse JSON array with JavaScript?

Spread the love

Sometimes, we want to parse JSON array with JavaScript.

In this article, we’ll look at how to parse JSON array with JavaScript.

How to parse JSON array with JavaScript?

To parse JSON array with JavaScript, we call the JSON.parse method.

For instance, we write

const myMessage = `
{
  "success": true,
  "counters": [
    {
      "counterName": "dsd",
      "counterType": "sds",
      "counterUnit": "sds"
    },
    {
      "counterName": "gdg",
      "counterType": "dfd",
      "counterUnit": "ds"
    }
  ]
}
`;

const jsonData = JSON.parse(myMessage);
for (const counter of jsonData.counters) {
  console.log(counter.counterName);
}

to call JSON.parse with the myMessage string.

Then we loop through the parsed jsonData object’s counters array property with a for-of loop.

In it, we get the counterName property of each object with counter.counterName.

Conclusion

To parse JSON array with JavaScript, we call the JSON.parse method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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