json

Convert JSON to JavaScript object using JSON.parse

In this article, we will discuss about converting a JSON text to JavaScript object.
 

JSON.parse

 
We can convert JSON to JavaScript object using JSON.parse method.

Its signature is :


JSON.parse(text [, reviver]);

 
JSON.parse takes two arguments :

1: A valid json text

2 : A reviver (Optional)
 

JSON.parse(text)

 

<!DOCTYPE html>
<html>
<body>

<h2>Parsing String to JSON</h2>

<p id="jsonparsing"></p>

<script>
var employeeJSON = '{"name":"John Doe","age":24,"address":"123 LasVegas Blvd"}';
var employeeObj = JSON.parse(employeeJSON);

document.getElementById("jsonparsing").innerHTML =
"Name = " + employeeObj.name + "<br/> Age = " + employeeObj.age + "<br/> Address = " + employeeObj.address;
console.log(employeeObj);
</script>

</body>
</html>

 

 

JSON.parse(text) with reviver

 
The reviver parameter is a function that takes two parameters: a key and a value.

We can use this function to transform each key/value pair as it is parsed.
 


var reviver = function(k,v);

var employeeObj = JSON.parse(employeeJSON, reviver);


 
If you supply a reviver function, the transformed value is returned in the parse() function output.

If the reviver function returns undefined for any pair, the property is deleted from the final result.

JSON accepts dates as strings. We could use a reviver to convert it to date.

We could also use this for custom transformations.

 
Here is an example :
 

<!DOCTYPE html>
<html>
<body>

<h2>Parsing String to JSON with reviver</h2>

<p id="jsonparsing"></p>

<script>
var employeeJSON = '{"name":"John Doe","age":24,"joinDate" : "Mar 30, 2010","address":"123 LasVegas Blvd"}';

var employeeObj = JSON.parse(employeeJSON,
  function reviver(k, v) {
    if (k == "name") {
      v = "Mr./Ms. " + v;
    }
    if(k == "joinDate"){
    v= new Date(v);
    }
   return v;
  });

document.getElementById("jsonparsing").innerHTML =
  "Name = " + employeeObj.name + "<br/> Age = " + employeeObj.age + "<br/> Joining Date = " + employeeObj.joinDate + "<br/> Address = " + employeeObj.address;
console.log(employeeObj);
</script>

</body>
</html>

 

 
 

You may also like :

Convert Javascript values to JSON using stringify

Parsing JSON in jQuery

JSON Basics

XML vs JSON

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

One comment

  1. these tools may help json lovers http://codebeautify.org/jsonviewer and http://jsonformatter.org

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: