简体   繁体   English

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

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

Why doesn't JSON.stringify() display prop2?为什么 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
}

JSFIDDLE: http://jsfiddle.net/egret230/efGgT/ JSFIDDLE: http://jsfiddle.net/egret230/efGgT/

Because JSON cannot store functions. 因为JSON无法存储函数。 According to the spec, a value must be one of: 根据规范,值必须是以下之一:

有效的JSON值
(source: json.org ) (来源: json.org


As a side note, this code will make the functions noticed by JSON.stringify : 作为旁注,此代码将使JSON.stringify注意到这些函数:

Function.prototype.toJSON = function() { return "Unstorable function" }

Here is another way with using a .prototype. 这是使用.prototype的另一种方法。 You can add an function to stringify 您可以添加一个函数来stringify

JSON.stringify(obj, function(k, v) {
  if (typeof v === 'function') {
    return v + '';
  }
  return v;
});

It's not supposed to stringify methods (or any functions) - especially since most methods of built in objects (and thus the prototypes of any user-defined objects) are native code. 它不应该对方法(或任何函数)进行字符串化 - 特别是因为大多数内置对象的方法(以及任何用户定义对象的原型)都是本机代码。

If you really need it to print your methods out, you can override your object's .toString method, but when you call JSON.parse on the stringified output, it will treat the method as if it were just a string, and to be able to call it as a function you'd have to eval it - a practice that is typically not recommended. 如果你真的需要它来打印你的方法,你可以覆盖你的对象的.toString方法,但是当你在字符串化的输出上调用JSON.parse时,它会把方法视为只是一个字符串,并且能够把它称为一个你必须eval它的功能 - 这种做法通常不推荐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM