How to deserialize a JSON into Javascript object?


Serialization is the process of converting an object such that it is transferable over the network. In JavaScript usually we serialize an Object into the JSON (or JavaScript Object Notation) format.

To reserialize a JSON into a JavaScript object, we need to use the method JSON.parse().

JavaScript object notation is used to exchange data to or from a web server of the rest full API. The data we get from a web server is always a string variable, in order to use it we need to parse it with JSON.parse() which will return a JavaScript object or array object. Following is the syntax of the parse() method

JSON.parse(string, function);

The JSON.parse() method always takes its argument in string format (i.e. we have to wrap the value with-in single inverted commas).

Example 1

In the following example, we are passing a variable named text and converting it into an object format using the JSON.parse() method.

<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
   <script>
      var text = '{"name":" Aman Kumar","Company":"TutorialsPoint", "city":"Hyderabad"}';
      var obj = JSON.parse(text);
      document.write(JSON.stringify(obj));
   </script>
</body>
</html>

Example 2

In the following example, we directly pass a text value to the JSON.parse() method. After the conversion of the data, we are printing the contents of the resultant object into a paragraph tag.

<!DOCTYPE html>
<html lang="en">
<head> </head>
<body>
<p id="demo"></p>
   <script>
      var obj = JSON.parse(
         '{"name":" Aman Kumar","Company":"TutorialsPoint", "city":"Hyderabad"}'
      );
      document.getElementById("demo").innerHTML =
      obj.name + " " + obj.Company + " " + obj.city;
   </script>
</body>
</html>

Example 3

In the following example, we pass an array of string elements into JSON.parse() method.

<html>
<body>
   <h2>Parsing a JSON Array.</h2>
   <p>JSON array will be parsed into a JavaScript array.</p>
   <p id="demo"></p>
   <script>
      const text = '[ "Tutorial", "Point", "Telangana", "Hyderabad" ]';
      const JSArr = JSON.parse(text);
      document.getElementById("demo").innerHTML = JSArr;
   </script>
</body>
</html>

Example 4

Let us see another example for this −

<html>
<body>
   <script>
      const json = '{"result":true, "count":42}';
      // Parse the object
      const obj = JSON.parse(json);
      document.write(obj.count,"<br>");
      document.write(obj.result);
   </script>
</body>
</html>

Updated on: 19-Dec-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements