JSON.stringify() method not only stringifies an object but also removes any function present in an object. Lets' discuss it in detail.
Example-1
In the following example, the property 'designation' is a function so when we tried to stringify the object, the function was removed and other properties were displayed as shown in the output.
<html> <body> <p id="stringify"></p> <script> var person = { name: "Rahim", designation: function () {return developer;}, city: "Hyderabad" }; var myJSON = JSON.stringify(person); document.getElementById("stringify").innerHTML = myJSON; </script> </body> </html>
Output
{"name":"Rahim","city":"Hyderabad"}
Example-2
In the following example, the property 'name' is acting as a function so when we stringify the object using JSON.stringify(), the function was removed and other properties were displayed as shown in the output.
<html> <body> <p id="stringify"></p> <script> var person = { name: function () {return Ram + Rahim;}, designation:"Developer" , city: "Hyderabad" }; var myJSON = JSON.stringify(person); document.getElementById("stringify").innerHTML = myJSON; </script> </body> </html>
Output
{"designation":"Developer","city":"Hyderabad"}