<!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对象用法</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转为字符串存到变量里
console.log(students);
localStorage.setItem("students",students);//将变量存到localStorage里
var newStudents = localStorage.getItem("students");
newStudents = JSON.parse(students); //转为JSON
console.log(newStudents); // 打印出原先对象
// alert(newStudents.length);
alert(newStudents.xiaomin.name);
//json数组类型字符串取值
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);//转换为json对象
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>
面对现在移动端的迅速发展,提供数据的方式不在是以前的PC-->PC界面了,这促使了JSON格式的使用,在H5以前的JS中,我在前面的一个H4中JS对JSON中的处理提到了eval方法,eval() ,在H5中JSON与String的转换如下:
以上所述是小编给大家介绍的HTML5中使用json对象的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!