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"}]}