Javascript parse json string

JSON.parse() can be used to parse a given json string into javascript value (array, string, etc.)

Here are some examples

Example – parse json containing string

<pre></pre>

<script>
  var v = '"str1"';
  jsVal = JSON.parse(v);
  document.querySelector("pre").innerText = typeof(jsVal);
</script>
refresh

Example – parse json containing array

<pre></pre>

<script>
  var v = '["val1", "val2", "val3"]';
  jsVal = JSON.parse(v);
  document.querySelector("pre").innerText = typeof(jsVal) + " jsVal[0]=" + jsVal[0];
  
</script>
refresh

Example – parse json containing object

<pre></pre>

<script>
  var v = '{ "x": "val1", "y": "val2", "z": "val3"}';
  jsVal = JSON.parse(v);
  document.querySelector("pre").innerText = typeof(jsVal) + ' jsVal["x"]=' +  jsVal["x"];
</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