Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
486 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...