本文實例講述了JavaScript解析JSON數據。分享給大家供大家參考,具體如下:
JSON數據是一種常用的數據格式,解析方式也比較簡單,特別是由于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":"數據2"}}{"字段3":{"地址3":"數據3"}} var jsonStr = '[{/"字段1/":{/"地址1/":/"數據1/"}},{/"字段2/":{/"地址2/":/"數據2/"}},{/"字段3/":{/"地址3/":/"數據3/"}}]'; var json = JSON.parse(jsonStr); // 將字符串轉換為JSON對象 // 循環遍歷獲取key -- value for(var i = 0; i < json.length; i++){ // {"字段1":{"地址1":"數據1"}} var itemJson = json[i]; // 再次遍歷獲取 for(var key in itemJson){ console.log(key); // {"地址2":"數據2"} var childItem = itemJson[key]; // 再次遍歷獲取 for (var keyItem in childItem) { console.log(keyItem + " -- " + childItem[keyItem]); } } }}</script></head><body><p>數據:</p><p>[{'字段1':{'地址1':'數據1'}},{'字段2':{'地址2':'數據2'}}{'字段3':{'地址3':'數據3'}}]</p><button type="button" onclick="startParse()">開始解析</button></body></html>
運行結果:
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答