jQuery 1.4.1中缺少JSON stringify功能?

74

显然,jQuery具有将给定对象或字符串解码为JSON对象的能力。但是,我有一个需要通过POST方式发送回服务器的JS对象,我发现在jQuery中没有封装JSON.stringify()函数的实用程序。该函数在Chrome、Safari 4、FF3.6和IE8中可以找到,但在早期浏览器中找不到。我可以在支持它的浏览器中本地使用它,但否则必须退回到使用Crockford的JSON脚本。

是否有内置于jQuery中的JSON编码和解码处理程序,可以取代Crockford脚本?


3
好的,我会尽力进行翻译。以下是需要翻译的内容:Similar post: https://dev59.com/T3VC5IYBdhLWcg3ww0Hr - sberry
也许我真的很蠢,但这对我来说完全是个惊喜。看起来JSON.org的脚本是正确的选择。 - KevinM
6个回答

29

10
是的,有点遗憾 jQuery 没有直接添加一个方法来做这件事。我最终使用 Closure 编译器压缩了 json.js 并将其置于我正在工作的 js 文件底部。这样可以解决问题,但感觉有些不必要。 - Geuis
我一直在使用http://code.google.com/p/jquery-json/的解决方案。对我来说很好用。 - crsuarezf
链接已失效。这个答案并没有真正给出答案,因为它只是一个链接。 - Josh Maag

27
你可以使用"闭包库"(Google)来制作跨浏览器的JSON编码器/解码器。
只需转到http://closure-compiler.appspot.com/ 并将以下内容插入文本框中,然后点击“编译”。
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @use_closure_library true
// ==/ClosureCompiler==

goog.require('goog.json');
if (!window['JSON']) window['JSON']={};
if (typeof window['JSON']['stringify'] !== 'function') window['JSON']['stringify']=goog.json.serialize;
if (typeof window['JSON']['parse'] !== 'function') window['JSON']['parse']=goog.json.parse;

我认为应该将 serialize 更改为 stringify,以便在可能的情况下重用浏览器的本地函数。 - Tomas
1
将 JSON.serialize 重命名为 JSON.stringify。 - stewe

14

1
@zcrar70,他特别要求一个JSON.stringify包装器...除非你的评论是针对OP的。 - Gabriele Petrioli

3

jQuery内部不需要此功能,因此没有提供方便的方法来实现此功能。

JSON.stringify()是一种将对象编码为该对象的JSON字符串表示的标准和推荐方式。它是许多浏览器中本地JSON对象的方法,并建议您使用json2.js(https://github.com/douglascrockford/JSON-js)提供备用方案。


2
继承stewe的答案,启用高级选项的闭包编译器会生成一个脚本,其中污染了全局命名空间中的一堆单字母变量。因此,我只需将其包装在匿名函数调用中,如下所示:
(function() {
  function g(a) {
    var b = typeof a;
    if ("object" == b)
      if (a) {
        if (a instanceof Array) return "array";
        if (a instanceof Object) return b;
        var c = Object.prototype.toString.call(a);
        if ("[object Window]" == c) return "object";
        if ("[object Array]" == c || "number" == typeof a.length && "undefined" != typeof a.splice && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("splice")) return "array";
        if ("[object Function]" == c || "undefined" != typeof a.call && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("call")) return "function"
      } else return "null";
    else if ("function" == b && "undefined" == typeof a.call) return "object";
    return b
  };

  function h(a) {
    a = "" + a;
    if (/^\s*$/.test(a) ? 0 : /^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g, "@").replace(/"[^"\\\n\r\u2028\u2029\x00-\x08\x10-\x1f\x80-\x9f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g, ""))) try {
      return eval("(" + a + ")")
    } catch (b) {}
    throw Error("Invalid JSON string: " + a);
  }

  function i(a, b) {
    var c = [];
    j(new k(b), a, c);
    return c.join("")
  }

  function k(a) {
    this.a = a
  }

  function j(a, b, c) {
    switch (typeof b) {
      case "string":
        l(b, c);
        break;
      case "number":
        c.push(isFinite(b) && !isNaN(b) ? b : "null");
        break;
      case "boolean":
        c.push(b);
        break;
      case "undefined":
        c.push("null");
        break;
      case "object":
        if (null == b) {
          c.push("null");
          break
        }
        if ("array" == g(b)) {
          var f = b.length;
          c.push("[");
          for (var d = "", e = 0; e < f; e++) c.push(d), d = b[e], j(a, a.a ? a.a.call(b, "" + e, d) : d, c), d = ",";
          c.push("]");
          break
        }
        c.push("{");
        f = "";
        for (e in b) Object.prototype.hasOwnProperty.call(b, e) && (d = b[e], "function" != typeof d && (c.push(f), l(e, c), c.push(":"),
          j(a, a.a ? a.a.call(b, e, d) : d, c), f = ","));
        c.push("}");
        break;
      case "function":
        break;
      default:
        throw Error("Unknown type: " + typeof b);
    }
  }
  var m = {
      '"': '\\"',
      "\\": "\\\\",
      "/": "\\/",
      "\u0008": "\\b",
      "\u000c": "\\f",
      "\n": "\\n",
      "\r": "\\r",
      "\t": "\\t",
      "\x0B": "\\u000b"
    },
    n = /\uffff/.test("\uffff") ? /[\\\"\x00-\x1f\x7f-\uffff]/g : /[\\\"\x00-\x1f\x7f-\xff]/g;

  function l(a, b) {
    b.push('"', a.replace(n, function(a) {
      if (a in m) return m[a];
      var b = a.charCodeAt(0),
        d = "\\u";
      16 > b ? d += "000" : 256 > b ? d += "00" : 4096 > b && (d += "0");
      return m[a] = d + b.toString(16)
    }), '"')
  };
  window.JSON || (window.JSON = {});
  "function" !== typeof window.JSON.stringify && (window.JSON.stringify = i);
  "function" !== typeof window.JSON.parse && (window.JSON.parse = h);
})();

现在你可以调用:

var JSONString = JSON.stringify({name: 'value'});


1
通常在使用jQuery时,不需要使用JSON.stringify()函数。例如,在使用ajax将JavaScript数据发送到服务器的常见情况下,jQuery已经内置了处理此类情况的函数:(示例来自http://api.jquery.com/category/ajax/
$.post("test.php", { name: "John", time: "2pm" } );
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) {
    alert("JSON Data: " + json.users[3].name);
});

在上述所有示例中,JavaScript 数据都是由 jQuery 自动序列化的。
在这些情况下,序列化不同于 JSON.Stringify(),而是将数据序列化为 HTML 查询字符串(参见:http://en.wikipedia.org/wiki/Query_string#Structure)。
然而,对于大多数应用程序来说,这种序列化形式是可以接受的(但并非全部)。

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