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.