<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"/>
<title>json對(duì)象用法</title>
<link rel="stylesheet" href="//g.alicdn.com/de/prismplayer/2.6.0/skins/default/aliplayer-min.css" />
<script type="text/javascript" src="//g.alicdn.com/de/prismplayer/2.6.0/aliplayer-min.js"></script>
</head>
<body>
<div class="prism-player" id="J_prismPlayer" style="position: absolute"></div>
<script>
var students = {
xiaomin: {
name: "xiaoming",
grade: 1
},
teemo: {
name: "teemo",
grade: 3
}
}
students = JSON.stringify(students); //將JSON轉(zhuǎn)為字符串存到變量里
console.log(students);
localStorage.setItem("students",students);//將變量存到localStorage里
var newStudents = localStorage.getItem("students");
newStudents = JSON.parse(students); //轉(zhuǎn)為JSON
console.log(newStudents); // 打印出原先對(duì)象
// alert(newStudents.length);
alert(newStudents.xiaomin.name);
//json數(shù)組類型字符串取值
var jsonStr = '[{"id":"01","open":false,"pId":"0","name":"A部門"},{"id":"01","open":false,"pId":"0","name":"A部門"},{"id":"011","open":false,"pId":"01","name":"A部門"},{"id":"03","open":false,"pId":"0","name":"A部門"},{"id":"04","open":false,"pId":"0","name":"A部門"}, {"id":"05","open":false,"pId":"0","name":"A部門"}, {"id":"06","open":false,"pId":"0","name":"A部門"}]';
var jsonObj = JSON.parse(jsonStr);//轉(zhuǎn)換為json對(duì)象
for(var i=0;i<jsonObj.length;i++){
alert(jsonObj[i].id); //取json中的值
}
console.log(jsonObj)
var jsonStr1 = JSON.stringify(jsonObj)
console.log(jsonStr1+"jsonStr1")
</script>
</body>
</html>
面對(duì)現(xiàn)在移動(dòng)端的迅速發(fā)展,提供數(shù)據(jù)的方式不在是以前的PC-->PC界面了,這促使了JSON格式的使用,在H5以前的JS中,我在前面的一個(gè)H4中JS對(duì)JSON中的處理提到了eval方法,eval() ,在H5中JSON與String的轉(zhuǎn)換如下:
以上所述是小編給大家介紹的HTML5中使用json對(duì)象的實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!