Categories
JavaScript Answers

How to Convert a JSON String to a JavaScript Object with JavaScript?

Spread the love

Sometimes, we want to convert a JSON string into a JavaScript object.

In this article, we’ll look at how to convert a JSON string to a JavaScript object.

Use the JSON.parse Method

We can use the JSON.parse method to convert a JSON string into a JavaScript object.

For instance, we can write:

const string = `
  {
    "foo": 1,
    "bar": 2
  }
`
const obj = JSON.parse(string);
console.log(obj)

We have a string with a JSON object as its content.

Then we pass string into JSON.parse to parse it into an object and assign it to obj .

Therefore, obj is:

{
  "foo": 1,
  "bar": 2
}

as we expect.

JSON.parse is available in all modern browsers so we can use it anywhere.

Conclusion

We can use the JSON.parse method to parse a JSON object string into a JavaScript object.

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 *