Computer >> Computer tutorials >  >> Programming >> Javascript

How not to delete a function inside an object when JSON.stringify() method is operated?


JSON.stringify() method not only stringifies an object but also removes any function if found inside that object. So to make the function not to be deleted it should be converted into a string and then only JSON.stringify() method should be applied.

In the following example since the function is not converted into a string, it is deleted when operated by JSON.stringify() method and other properties were displayed as shown in the output.

Example

<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"}

 

In the following example, before getting operated by JSON.stringify() method, the function was converted to a string using toString() method. So the function was not deleted when operated by JSON.stringify() method.

Example

<html>
<body>
<p id="stringify"></p>
<script>
   var obj = { name: function () {return Ram + Rahim;},
   designation:"Developer" , city: "Hyderabad" };
   obj.name = obj.name.toString();
   var myJSON = JSON.stringify(obj);
   document.getElementById("stringify").innerHTML = myJSON;
</script>
</body>
</html>

Output

{"name":"function () {return Ram + Rahim;}","designation":"Developer","city":"Hyderabad"}