How to convert a JSON string into a JavaScript object?


Javascript has provided JSON.parse() method to convert a JSON into an object. Once JSON is parsed we can able to access the elements in the JSON.

syntax

var obj = JSON.parse(JSON);

It takes a JSON and parses it into an object so as to access the elements in the provided JSON.

Example-1

In the following example, a JOSN is assigned to a variable and converted it into an object and later on displayed the values of the elements in the JSON as shown in the output.

Live Demo

<html>
<body>
<script>
   var json = '{"name": "Malinga", "age": 32, "country": "srilanka"}';
   var obj = JSON.parse(json);
   document.write(obj.name + "</br>");
   document.write(obj.age + "</br>");
   document.write(obj.country);
</script>
</body>
</html>

Output

Malinga
32
srilanka


Example-2

Live Demo

<html>
<body>
<script>
   var json = '{"company": "Tutorialspoint", "Product": "Tutorix", "city": "Hyderabad"}';
   var obj = JSON.parse(json);
   document.write(obj.company+ "</br>");
   document.write(obj.Product+ "</br>");
   document.write(obj.city);
</script>
</body>
</html>

Output

Tutorialspoint
Tutorix
Hyderabad
raja
Published on 01-Aug-2019 12:30:25
Advertisements