为什么JSON.stringify不显示作为函数的对象属性?

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)

  • @Derek:`JSON.stringify`省略了'undefined`值的成员.设置为"undefined"的变量与从未设置的变量无法区分. (3认同)
  • @apsillers:...至少从JSON视图.将属性设置为undefined将创建该属性. (2认同)
  • `Function.prototype.toJSON` 不错! (2认同)

Zim*_*Zim 5

这是使用 .prototype 的另一种方法。您可以添加一个函数来字符串化

JSON.stringify(obj, function(k, v) {
  if (typeof v === 'function') {
    return v + '';
  }
  return v;
});
Run Code Online (Sandbox Code Playgroud)