2010-02-17 59 views
74

显然,jQuery有能力将给定的对象或字符串解码为JSON对象。然而,我有一个JS对象,我需要回发到服务器,并且我发现jQuery中没有包装JSON.stringify()函数的实用程序。该功能可在Chrome,Safari 4,FF3.6和IE8中找到,但在早期的浏览器中找不到。我可以在支持它的浏览器中本地使用它,但否则会被迫退回到使用Crockford的JSON脚本。从jQuery 1.4.1中缺少JSON stringify?

是否有一些内置的jQuery处理JSON编码和解码,取代了Crockford脚本?

+3

类似的帖子:HTTP://计算器。com/questions/191881/serializing-to-json-in-jquery – sberry

+0

也许我真的很笨,但这对我来说也是一个完全的惊喜。看起来像JSON.org的脚本是要走的路。 – KevinM

回答

30

您可能要检查了这一点: http://www.json.org/js.html

+10

是的,它的一种悲伤,jQuery没有添加一个方法直接对库执行此操作。我最终用Closure编译器对json.js进行了简化,并将其放在我正在工作的js文件的底部。它会做的伎俩,但似乎没有必要。 – Geuis

+0

我一直在使用http://code.google.com/p/jquery-json/解决方案。对我来说工作得很好。 – crsuarezf

14

jQuery的可以与原生JSON jQuery.parseJSON()字符串解码。

对于编码不过,我只知道一个插件:jquery-json

+2

直接使用JSON.stringify有什么问题? – zcrar70

+1

@ zcrar70,他特别要求提供'JSON.stringify'包装器,除非您的评论是针对OP的。 –

+0

所以他这样做,我的道歉。 – zcrar70

26

您可以使用“封库”(谷歌),使一个跨浏览器的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; 
+0

我认为'serialize'应该改为'stringify'来重用浏览器原生函数(如果可用) – Tomas

+1

将这个JSON.serialize重命名为JSON.stringify – stewe

+0

就像这样! –

3

jQuery的内部并不需要此功能,因此不提供一个便捷方法这样做。

JSON.stringify()是将对象编码为该对象的JSON字符串表示形式的标准和推荐方法。这是很多浏览器的原生JSON对象的方法,并建议您使用json2.js(https://github.com/douglascrockford/JSON-js)提供后备。

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)。

但是这种形式的序列化是适用于大多数(但不是全部)应用

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'});