Javascript:stringify对象(包括类型函数的成员)

Yan*_*roo 21 javascript serialization json function stringify

我正在寻找一种解决方案,将Javascript对象序列化(和反序列化)到跨浏览器的字符串,包括碰巧是函数的对象的成员.典型的对象如下所示:

{
   color: 'red',
   doSomething: function (arg) {
        alert('Do someting called with ' + arg);
   }
}
Run Code Online (Sandbox Code Playgroud)

doSomething()只包含局部变量(不需要序列化调用上下文!).

JSON.stringify()将忽略'doSomething'成员,因为它是一个函数.我知道toSource()方法会做我想要的,但它是FF特定的.

CD.*_*D.. 8

你可以使用JSON.stringify一个replacer像:

JSON.stringify({
   color: 'red',
   doSomething: function (arg) {
        alert('Do someting called with ' + arg);
   }
}, function(key, val) {
        return (typeof val === 'function') ? '' + val : val;
});
Run Code Online (Sandbox Code Playgroud)

  • 我最终使用`JSON.stringify(myObject,function(key,val){return(typeof val ==='function')?'[function]':val;},4);`并输出非常好. (2认同)

Moo*_*Goo 7

快速而肮脏的方式是这样的:

Object.prototype.toJSON = function() {
  var sobj = {}, i;
  for (i in this) 
    if (this.hasOwnProperty(i))
      sobj[i] = typeof this[i] == 'function' ?
        this[i].toString() : this[i];

 return sobj;

};
Run Code Online (Sandbox Code Playgroud)

显然这会影响代码中每个对象的序列化,并且可能会使用未经过滤的for in循环来绊倒niave代码."正确"的方法是编写一个递归函数,该toJSON函数将在任何给定对象的所有后代成员上添加函数,处理循环引用等.但是,假设单线程Javascript(没有Web Workers),此方法应该工作,不会产生任何意外的副作用.

必须在Array的原型中添加类似的函数,以通过返回数组而不是对象来覆盖Object.另一种选择是附加一个选项,让它根据对象自身的性质选择性地返回一个数组或一个对象,但它可能会更慢.

function JSONstringifyWithFuncs(obj) {
  Object.prototype.toJSON = function() {
    var sobj = {}, i;
    for (i in this) 
      if (this.hasOwnProperty(i))
        sobj[i] = typeof this[i] == 'function' ?
          this[i].toString() : this[i];

    return sobj;
  };
  Array.prototype.toJSON = function() {
      var sarr = [], i;
      for (i = 0 ; i < this.length; i++) 
          sarr.push(typeof this[i] == 'function' ? this[i].toString() : this[i]);

      return sarr;
  };

  var str = JSON.stringify(obj);

  delete Object.prototype.toJSON;
  delete Array.prototype.toJSON;

  return str;
}
Run Code Online (Sandbox Code Playgroud)

http://jsbin.com/yerumateno/2/edit

  • 解析函数会是什么样的?所有函数都在字符串中,因此在解析时我们需要将它们转换回函数. (3认同)