JSON.stringify()在使用Prototype.js的数组时表现异常

90

我正在试图弄清楚我的JSON序列化出了什么问题,我有当前版本和旧版本的应用程序,并发现JSON.stringify()的工作方式存在一些令人惊讶的差异(使用来自json.org的JSON库)。

在旧版本的应用程序中:

 JSON.stringify({"a":[1,2]})

给我了这个;

"{\"a\":[1,2]}"

在新版本中,

 JSON.stringify({"a":[1,2]})

给我这个:

"{\"a\":\"[1, 2]\"}"

你有什么想法,是什么改变导致同一个库在新版本中给数组括号加上了引号?


4
似乎是与Prototype库发生冲突,这是我们在较新版本中引入的。有什么办法将包含数组的JSON对象字符串化在Prototype下? - morgancodes
27
因此,人们应该避免篡改全局内置对象(如原型框架所做的那样)。 - Gerardo Lima
11个回答

0
如果您不想全部清除,且需要一段在大多数浏览器上都能正常运行的代码,您可以这样做:
(function (undefined) { // This is just to limit _json_stringify to this scope and to redefine undefined in case it was
  if (true ||typeof (Prototype) !== 'undefined') {
    // First, ensure we can access the prototype of an object.
    // See https://dev59.com/dWsz5IYBdhLWcg3wy689
    if(typeof (Object.getPrototypeOf) === 'undefined') {
      if(({}).__proto__ === Object.prototype && ([]).__proto__ === Array.prototype) {
        Object.getPrototypeOf = function getPrototypeOf (object) {
          return object.__proto__;
        };
      } else {
        Object.getPrototypeOf = function getPrototypeOf (object) {
          // May break if the constructor has been changed or removed
          return object.constructor ? object.constructor.prototype : undefined;
        }
      }
    }

    var _json_stringify = JSON.stringify; // We save the actual JSON.stringify
    JSON.stringify = function stringify (obj) {
      var obj_prototype = Object.getPrototypeOf(obj),
          old_json = obj_prototype.toJSON, // We save the toJSON of the object
          res = null;
      if (old_json) { // If toJSON exists on the object
        obj_prototype.toJSON = undefined;
      }
      res = _json_stringify.apply(this, arguments);
      if (old_json)
        obj_prototype.toJSON = old_json;
      return res;
    };
  }
}.call(this));

这看起来很复杂,但只是为了处理大多数用例而复杂。 主要思路是重写 JSON.stringify ,从作为参数传递的对象中移除 toJSON ,然后调用旧的 JSON.stringify ,最后恢复它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接