Javascript convert array to json string

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>
refresh

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>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments