本文實例分析了JSON字符串和對象相互轉換方法。分享給大家供大家參考,具體如下:
同事問了我一個問題――server端返回了一個json結構的字符串,怎么樣去訪問json對象里面的值?jquery有沒有對返回的JSON數據進行解析?
我自己寫了一個小的demo,還有從網上查了一些資料,在這里跟大家分享一下
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><script src="jquery-1.6.2.min.js" type="text/javascript"></script><script type="text/javascript">$(document).ready( function(){ var json = {"name":"Mike","sex":"女","age":29}; alert(typeof json); var temp = obj2str(json); alert(temp); alert(typeof temp); });//下面這個方法是將json對象轉換為字符串function obj2str(o){ var r = []; if(typeof o =="string") return "/""+o.replace(/([/'/"http://])/g,"http://$1").replace(/(/n)/g,"http://n").replace(/(/r)/g,"http://r").replace(/(/t)/g,"http://t")+"/""; if(typeof o =="undefined") return "undefined"; if(typeof o == "object"){ if(o===null) return "null"; else if(!o.sort){ for(var i in o) r.push(i+":"+obj2str(o[i])) r="{"+r.join()+"}" }else{ for(var i =0;i<o.length;i++) r.push(obj2str(o[i])) r="["+r.join()+"]" } return r; } return o.toString();}/*使用jquery插件,需要注意的是json的key-value必須都為字符串,即都需要使用雙引號包起來,不能使用單引號,如果value是數字就不需要用雙引號包起來*/function jquery_string_to_json(){ var jsonString = '{"name":"huangbiao","sex":"boy","age":16}'; //var jsonString = "{'name':'huangbiao','sex':'boy','age':16}";//錯誤的聲明 alert(typeof jsonString); var obj = jQuery.parseJSON(jsonString); alert(typeof obj);}/*使用eval方法對于字符串里面的key-value都必須使用雙引號括起來,不能使用單引號,否則不能夠正常解析*/function String_to_JSON(){ var json = '{"name":"huangbiao","sex":"boy","age":16}'; var temp = eval('('+json+')');//eval方法里面的括號是不能夠少的,否則報腳本錯誤 alert(typeof temp); alert(temp.name); //使用JSON對象只能在IE8以上的版本支持,因此不建議使用這種方式轉換 //var json = '{"name":"Mike","sex":"女","age":"29"}'; //var temp = JSON.parse(json); //alert(temp.name);}</script><title>無標題文檔</title></head><body></body></html>
在工作中發現server端傳給前端JSON格式的字符串,使用eval("("+json+")");沒有辦法將得到的字符串轉換為JSON對象,解決辦法如下:
function obj2str(o){ var r = []; if(typeof o =="string") return "/""+o.replace(/([/'/"http://])/g,"http://$1").replace(/(/n)/g,"http://n").replace(/(/r)/g,"http://r").replace(/(/t)/g,"http://t")+"/""; if(typeof o =="undefined") return "undefined"; if(typeof o == "object"){ if(o===null) return "null"; else if(!o.sort){ for(var i in o) r.push(i+":"+obj2str(o[i])) r="{"+r.join()+"}" }else{ for(var i =0;i<o.length;i++) r.push(obj2str(o[i])) r="["+r.join()+"]" } return r; } return o.toString();}function json2obj(o){ var result = obj2str(o); return eval("(" + result + ")");}
調用json2obj(o)這個方法即可。
PS:這里再為大家推薦幾款json在線工具,相信大家在今后的開發中可以用得到:
在線JSON代碼檢驗、檢驗、美化、格式化工具:
http://tools.VeVB.COm/code/json
JSON在線格式化工具:
http://tools.VeVB.COm/code/jsonformat
在線XML/JSON互相轉換工具:
http://tools.VeVB.COm/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉換工具:
http://tools.VeVB.COm/code/jsoncodeformat
C語言風格/HTML/CSS/json代碼格式化美化工具:
http://tools.VeVB.COm/code/ccode_html_css_json
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript中json操作技巧總結》、《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答