Categories
JavaScript Answers

How to convert object string to JSON with JavaScript?

Spread the love

Sometimes, we want to convert object string to JSON with JavaScript.

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

How to convert object string to JSON with JavaScript?

To convert object string to JSON with JavaScript, we can use eval to convert the object string to valid JSON if the string is trusted for sure.

For instance, we write

const str =
  "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
const json = JSON.stringify(eval("(" + str + ")"));

to call eval on the str string to convert it to a valid JavaScript object.

Then we call JSON.stringify on the returned object to convert it to a valid JSON string.

Conclusion

To convert object string to JSON with JavaScript, we can use eval to convert the object string to valid JSON if the string is trusted for sure.

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 *