Why doesn't JSON.stringify display object properties, which are functions?

Why doesn't JSON.stringify () show prop2?

var newObj = { prop1: true, prop2: function(){ return "hello"; }, prop3: false }; alert( JSON.stringify( newObj ) ); // prop2 appears to be missing alert( newObj.prop2() ); // prop2 returns "hello" for (var member in newObj) { alert( member + "=" + newObj[member] ); // shows prop1, prop2, prop3 } 

JSFIDDLE: http://jsfiddle.net/egret230/efGgT/

+8
source share
3 answers

Because JSON cannot store functions. According to the specification, the value must be one of:

Valid JSON values
(source: json.org )


As a note, this code will make the functions noticed by JSON.stringify :

 Function.prototype.toJSON = function() { return "Unstorable function" } 
+18
source

Here is another way to use .prototype. You can add a function to reinforce

 JSON.stringify(obj, function(k, v) { if (typeof v === 'function') { return v + ''; } return v; }); 
+3
source

It is not intended to scribble methods (or any functions) - especially since most methods of built-in objects (and, therefore, prototypes of any user-defined objects) are native code.

If you really need to print your methods, you can override your .toString method, but when you call JSON.parse on the line output, it will process the method as if it were just a string, and be able to name it as a function, which you should use for eval is a practice that is usually not recommended.

+2
source

Source: https://habr.com/ru/post/916505/


All Articles