JSON.stringify() can be used to convert a given javascript value to json strng.
Usage:
JSON.stringify(value[, replacer[, space]])
Here are some examples
Example – JSON.stringify() default
This is default case with no indentation.
<pre></pre> <script> var a = { x: "val1", y: "val2", z: "val3"} jsonStr = JSON.stringify(a); document.querySelector("pre").innerText = jsonStr; </script>
Example – JSON.stringify() with readability indentation
Here are using 2 space indentation. This will also insert newlines appropriately.
<pre></pre> <script> var a = { x: "val1", y: "val2", z: "val3"} jsonStr = JSON.stringify(a, null, 2); document.querySelector("pre").innerText = jsonStr; </script>