Sometimes, we want to escape a JSON string to have it in a URL with JavaScript.
In this article, we’ll look at how to escape a JSON string to have it in a URL with JavaScript.
How to escape a JSON string to have it in a URL with JavaScript?
To escape a JSON string to have it in a URL with JavaScript, we can use the encodeURIComponent function.
For instance, we write
const str = encodeURIComponent(JSON.stringify(obj));
to convert the obj object to a JSON string with JSON.stringify.
Then we call encodeURIComponent with the JSON string to escape it to that it can be in a URL.
Conclusion
To escape a JSON string to have it in a URL with JavaScript, we can use the encodeURIComponent function.