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