egr*_*ret 8 javascript json function object stringify
为什么JSON.stringify()不显示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
}
Run Code Online (Sandbox Code Playgroud)
JSFIDDLE:http: //jsfiddle.net/egret230/efGgT/
Eri*_*ric 19
因为JSON无法存储函数.根据规范,值必须是以下之一:
有效的JSON值http://json.org/value.gif
作为旁注,此代码将使函数注意到JSON.stringify:
Function.prototype.toJSON = function() { return "Unstorable function" }
Run Code Online (Sandbox Code Playgroud)
这是使用 .prototype 的另一种方法。您可以添加一个函数来字符串化
JSON.stringify(obj, function(k, v) {
if (typeof v === 'function') {
return v + '';
}
return v;
});
Run Code Online (Sandbox Code Playgroud)