jQuery 1.4.1 中缺少 JSON 字符串化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2277405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON stringify missing from jQuery 1.4.1?
提问by Geuis
Apparently jQuery has the ability to decode a given object or string into a JSON object. However, I have a JS object that I need to POST back to the server and I find no utility in jQuery that wraps the JSON.stringify() function. That function is found in Chrome, Safari 4, FF3.6, and IE8 but is not found in earlier browsers. I can use it natively in the browsers that support it, but otherwise am forced to fall back to using Crockford's JSON scripts.
显然 jQuery 能够将给定的对象或字符串解码为 JSON 对象。但是,我有一个 JS 对象,我需要将其 POST 回服务器,并且我在 jQuery 中没有找到包装 JSON.stringify() 函数的实用程序。该功能可在 Chrome、Safari 4、FF3.6 和 IE8 中找到,但在早期浏览器中找不到。我可以在支持它的浏览器中本地使用它,但除此之外我不得不退回到使用 Crockford 的 JSON 脚本。
Is there some built-in with jQuery that handles JSON encoding and decoding that takes the place of the Crockford scripts?
是否有一些内置的 jQuery 来处理 JSON 编码和解码来代替 Crockford 脚本?
采纳答案by shinkou
You might want to check this out: http://www.json.org/js.html
你可能想看看这个:http: //www.json.org/js.html
回答by stewe
You can use "Closure Library" (Google) to make a cross browser JSON encoder/decoder.
您可以使用“Closure Library”(Google)来制作跨浏览器的 JSON 编码器/解码器。
Just go to http://closure-compiler.appspot.com/
只需访问http://closure-compiler.appspot.com/
and insert the following into the text field, then hit "Compile":
并将以下内容插入文本字段,然后点击“编译”:
// ==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;
回答by Gabriele Petrioli
jQuery can decode JSON strings natively with jQuery.parseJSON()
.
jQuery 可以使用jQuery.parseJSON()
.
For encoding though, i only know of a plugin : jquery-json
不过对于编码,我只知道一个插件:jquery-json
回答by Steve
jQuery does not need this functionality internally and thus does not provide a convenience method to do so.
jQuery 内部不需要此功能,因此不提供这样做的便捷方法。
JSON.stringify() is the standard and recommended way of encoding an object to a JSON string representation of that object. It is a method of the native JSON object in many browsers, and it is recommended you use json2.js (https://github.com/douglascrockford/JSON-js) to provide a fallback.
JSON.stringify() 是将对象编码为该对象的 JSON 字符串表示的标准和推荐方法。它是许多浏览器中原生 JSON 对象的一种方法,建议您使用 json2.js (https://github.com/douglascrockford/JSON-js) 提供回退。
回答by crizCraig
To build on stewe's answer, closure compiler with Advancedturned on gives you a script that pollutes the global namespace with a bunch of one letter variables. So, I just wrap it in an anonymous function call like so:
为了建立在steve的回答基础上,打开Advanced的闭包编译器为您提供了一个脚本,该脚本用一堆单字母变量污染全局命名空间。所以,我只是将它包装在一个匿名函数调用中,如下所示:
(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);
})();
Now you can call:
现在你可以调用:
var JSONString = JSON.stringify({name: 'value'});
var JSONString = JSON.stringify({name: 'value'});
回答by wal5hy
Often the JSON.stringify() function is not required when using jQuery. Take for example the common case of using ajax to send javascript data to the server, jquery has built-in functions to handle this: (examples from http://api.jquery.com/category/ajax/)
使用 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);
});
In all the examples above the javascript data sent is serialized by jQuery automatically.
在上面的所有示例中,发送的 javascript 数据由 jQuery 自动序列化。
The serialization in these cases is not the same as JSON.Stringify(), instead the data is serialised into a html query string (see: http://en.wikipedia.org/wiki/Query_string#Structure).
这些情况下的序列化与 JSON.Stringify() 不同,而是将数据序列化为 html 查询字符串(请参阅:http: //en.wikipedia.org/wiki/Query_string#Structure)。
However this form of serialization is fine for most (but not all) applications
然而,这种形式的序列化适用于大多数(但不是全部)应用程序