本文實(shí)例講述了JavaScript解析JSON數(shù)據(jù)。分享給大家供大家參考,具體如下:
JSON數(shù)據(jù)是一種常用的數(shù)據(jù)格式,解析方式也比較簡單,特別是由于JavaScript原生就支持JSON,所以JavaScript能夠更好的解析JSON。
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>解析JSON</title><script>// 開始解析function startParse(){ // ,{"字段2":{"地址2":"數(shù)據(jù)2"}}{"字段3":{"地址3":"數(shù)據(jù)3"}} var jsonStr = '[{/"字段1/":{/"地址1/":/"數(shù)據(jù)1/"}},{/"字段2/":{/"地址2/":/"數(shù)據(jù)2/"}},{/"字段3/":{/"地址3/":/"數(shù)據(jù)3/"}}]'; var json = JSON.parse(jsonStr); // 將字符串轉(zhuǎn)換為JSON對象 // 循環(huán)遍歷獲取key -- value for(var i = 0; i < json.length; i++){ // {"字段1":{"地址1":"數(shù)據(jù)1"}} var itemJson = json[i]; // 再次遍歷獲取 for(var key in itemJson){ console.log(key); // {"地址2":"數(shù)據(jù)2"} var childItem = itemJson[key]; // 再次遍歷獲取 for (var keyItem in childItem) { console.log(keyItem + " -- " + childItem[keyItem]); } } }}</script></head><body><p>數(shù)據(jù):</p><p>[{'字段1':{'地址1':'數(shù)據(jù)1'}},{'字段2':{'地址2':'數(shù)據(jù)2'}}{'字段3':{'地址3':'數(shù)據(jù)3'}}]</p><button type="button" onclick="startParse()">開始解析</button></body></html>
運(yùn)行結(jié)果:
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運(yùn)行工具:http://tools.VeVB.COm/code/HtmlJsRun測試上述代碼運(yùn)行效果。
PS:關(guān)于json操作,這里再為大家推薦幾款比較實(shí)用的json在線工具供大家參考使用:
在線JSON代碼檢驗(yàn)、檢驗(yàn)、美化、格式化工具:
http://tools.VeVB.COm/code/json
JSON在線格式化工具:
http://tools.VeVB.COm/code/jsonformat
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.VeVB.COm/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉(zhuǎn)換工具:
http://tools.VeVB.COm/code/jsoncodeformat
在線json壓縮/轉(zhuǎn)義工具:
http://tools.VeVB.COm/code/json_yasuo_trans
更多關(guān)于JavaScript相關(guān)內(nèi)容可查看本站專題:《JavaScript中json操作技巧總結(jié)》、《JavaScript查找算法技巧總結(jié)》、《JavaScript錯誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答