Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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/

like image 724
egret Avatar asked May 23 '12 23:05

egret


People also ask

What does JSON Stringify do with functions?

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.

Does JSON Stringify work on objects?

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.

Does JSON Stringify remove functions?

stringify() method not only stringifies an object but also removes any function if found inside that object.

What is specific properties are skipped by JSON Stringify method?

Following JS-specific properties are skipped by JSON.stringify method. Function properties (methods). Symbolic properties. Properties that store undefined.


1 Answers

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

Valid JSON values
(source: json.org)


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

Function.prototype.toJSON = function() { return "Unstorable function" }
like image 53
Eric Avatar answered Dec 20 '22 21:12

Eric