2010-02-17 33 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'});