HTML5已原生支持json的解析,window.JSON.parse()將json格式字符串轉換為json對象,window.JSON.stringify()將json對象轉換為json格式字符串。
示例:Html代碼?
<!DOCTYPE?HTML>?
<html>?
<head>?
<title>Window.JSON</title>?
<meta?charset="gb18030">?
</head>?
<body>?
<button?type="button"?id="btn1">解析json字符串</button>?
<button?type="button"?id="btn2">json對象轉換為json字符串</button>?
<div?id="res">?
</div>?
<script?language="JavaScript">?
<!--?
var?jsonStr?=?"{\"total\":100,\"data\":[{\"id\":10001,\"name\":\"scott\"},{\"id\":10002,\"name\":\"tiger\"}]}";?
var?jsonObj?=?window.JSON.parse(jsonStr);?
document.getElementById("btn1").onclick?=?function()?{?
var?str?=?"json字符串解析為json對象<br>";?
str?+=?"<span>Total:"+jsonObj.total+"</span><br><span>Data:";?
for?(var?i=0;i<jsonObj.data.length?;?i++)?
{?
str?+=?"id:"?+?jsonObj.data[i].id?+?",name:"?+?jsonObj.data[i].name+"<br>";?
}?
str?+=?"</span><br>";?
document.querySelector("#res").innerHTML?=?str;?
}?
document.getElementById("btn2").onclick?=?function()?{?
var?jsonObj?=?{total:100,data:[{id:10001,name:"scott"},{id:10002,name:"tiger"}]};?
var?jsonStr?=?window.JSON.stringify(jsonObj);?
var?str?=?"轉為json字符串:<br>"?+?jsonStr;?
document.querySelector("#res").innerHTML?=?str;?
}?
//-->?
</script>?
</body>?
</html>
單擊“解析json字符串”按鈕,結果:
json字符串解析為json對象
Total:100
Data:id:10001,name:scott
id:10002,name:tiger
單擊“json對象轉換為json字符串”按鈕,結果:
轉為json字符串:
{"total":100,"data":[{"id":10001,"name":"scott"},{"id":10002,"name":"tiger"}]}