當前位置:成語大全網 - 書法字典 - 請問如何用JavaScript解析JSON?

請問如何用JavaScript解析JSON?

(函數($){ $。toJSON =函數(o)

{ if(type of(JSON)=‘object‘& amp;& ampJSON.stringify)

返回JSON . stringify(o);var type = type of(o);if(o = = = null)

返回“null”;if(type = =“undefined“)

未定義的返回;if(type = =“number“| | type = =“boolean“)

return o+“;if(type = =“string“)

返回美元。quote string(o);if(type = =‘object‘)

{ if(type of o . tojson = =“function“)

返回美元。托吉森(o .托吉森());if(o . constructor = = = Date)

{ var month = o . getutcmonth()+1;if(月份& lt10)月=‘0‘+月;var day = o . getutcdate();if(day & lt;10)day =‘0‘+day;var year = o . getutcfullyear();var hours = o . getutchhours();if(小時& lt10)小時數=‘0‘+小時數;var minutes = o . getutc minutes();if(分鐘& lt10)分鐘=‘0‘+分鐘;var seconds = o . getutcseconds();if(秒& lt10)秒=‘0‘+秒;var milli = o . getutc milliseconds();if(milli & lt;100)毫=‘0‘+毫;if(milli & lt;10)毫=‘0‘+毫;返回“““+年+“-“+月+“-“+日+“T“+

‘小時+‘:‘+分鐘+‘:‘+秒+‘。‘+milli+‘Z“‘;}

if(o . constructor = = = Array)

{ var ret =【】;for(var I = 0;我& lto .長度;i++)

ret . push($。to JSON(o【I】)| |“null“);return“““+ret . join(“,““+“】“;}

var pairs =【】;for(var k in o){ var name;var type = type of k;if(type = =“number“)

name =“““+k+“““;else if(type = =“string“)

name=$。報價字符串(k);其他

繼續;if(type of o【k】= =“函數“)

繼續;var val=$。托克森(o【k】);pairs . push(name+“:“+val);}

返回“{“+pairs . join(“,““+“}“;}};$.evalJSON =函數(src)

{ if(type of(JSON)=‘object‘& amp;& ampJSON.parse)

返回JSON . parse(src);return eval(“(“+src+“);};$.secureEvalJSON = function(src)

{ if(type of(JSON)=‘object‘& amp;& ampJSON.parse)

返回JSON . parse(src);var filtered = srcfiltered = filtered . replace(/\ \【“\ \ \/bfn RTU】/g,‘@‘);filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-嗎?\d+(?:\.\d*)?(?:【eE】【+\-】?\d+)?/g,‘】‘);filtered = filtered . replace(/(?:^|:|,)(?:\ s * \【)+/g,““);if(/^[\],:{}\s]*$/.測試(過濾))

return eval(“(“+src+“);其他

拋出新語法錯誤(“解析JSON時出錯,源無效。”);};$.quoteString =函數(字符串)

{ if(string . match(_ escapeable))

{ return““+string . replace(_ escapeable,function(a))

{ var c = _ meta【a】;if(type of c = = =‘string‘)返回c;c = a . charcodeat();return‘\ \ u00‘+math . floor(c/16)。toString(16)+(c % 16)。toString(16);})+'"';}

返回“““+string+“““;};var _ escapeable =/【“\ \ \ x00-\ x 1f \ x7f-\ x9f】/g;var _ meta = {‘\ b‘:‘\ \ b‘,‘\ t‘:‘\ \ t‘,‘\ n‘:‘\ \ n‘,‘\ f‘:‘\ \ f‘,‘\ r‘:‘\ \ r‘,‘“‘:‘\ \ r‘,‘\‘:‘\ \“‘,‘\‘:‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘\‘})(jQuery);

將這段代碼復制到壹個文件中並保存為jquery-json.js引用後,jquery將擴展壹個方法到json。

例如var obj = { a:“1“,b:“2“};

然後是美元。to JSON(obj)是字符串“{‘a’:‘123’,‘b’:‘333’}”;

上面的插件來自googlecode,不是原創。只是我發鏈接的時候會被百度審核很久,所以我直接貼了別人的代碼。