Why doesn't JSON.stringify() display 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/
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
JSON. stringify() will encode values that JSON supports. Objects with values that can be objects, arrays, strings, numbers and booleans. Anything else will be ignored or throw errors.
stringify() method not only stringifies an object but also removes any function if found inside that object.
Following JS-specific properties are skipped by JSON.stringify method. Function properties (methods). Symbolic properties. Properties that store undefined.
Because JSON cannot store functions. According to the spec, a value must be one of:
(source: json.org)
As a side note, this code will make the functions noticed by JSON.stringify
:
Function.prototype.toJSON = function() { return "Unstorable function" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With