What is JSON.stringify() and explain its use in javascript?


JSON.stringify()

If we need to send data to a web server the data should be a string.To change the object literal to string JSON.stringify() method should be used.For instance

Example-1

 Live Demo

<html>
<body>
<p id="demo"></p>
<script>
   var obj = {name:"rekha", age:40, city:"newyork"};
   var myJSON = JSON.stringify(obj);
   document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>

Output

{"name":"rekha","age":40,"city":"newyork"}

Example-2

 Live Demo

<html>
<body>
<p id="demo"></p>
<script>
   var obj = {"name":"ramesh","age":30,"family":
          [{"mother":"geetha","father":"rao"}],"city":"berlin"};
   var myJSON = JSON.stringify(obj);
   document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>

Output

{"name":"ramesh","age":30,"family":[{"mother":"geetha","father":"rao"}],"city":"berlin"}

Updated on: 30-Jul-2019

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements