下面经由过程实例代码给人人引见HTML5中运用json对象的要领,细致代码以下所示:
<!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> <p class="prism-player" id="J_prismPlayer" style="position: absolute"></p> <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>
补充:下面看下Html5中JSON对象与String的相互转换
面临如今挪动端的迅速发展,供应数据的体式格局不在是之前的PC-->PC界面了,这促使了JSON花样的运用,在H5之前的JS中,我在前面的一个H4中JS对JSON中的处置惩罚提到了eval要领,eval() ,在H5中JSON与String的转换以下:
String转换为JSON对象:
var jsonObj; function myParse(){ var jsonStr=document.querySelector("#txtJsonStr").value; jsonObj=JSON.parse(jsonStr); }
JSON对象转换为String:
function myStringify(){ var txtJson=document.querySelector("#txtJsonStr"); var jsonStr2=JSON.stringify(jsonObj); //此处的jsonObj 是一个 JSON对象 xtJson.value=jsonStr2; }
总结
以上所述就是给人人引见的HTML5中运用json对象的实例代码,愿望能对人人的进修有所协助。更多相干教程请接见Html5视频教程!
相干引荐:
php公益培训视频教程
HTML5图文教程
HTML5在线手册
以上就是HTML5中运用json对象的实例代码的细致内容,更多请关注ki4网别的相干文章!