当前位置: 移动技术网 > IT编程>网页制作>Html5 > HTML5中使用json对象的实例代码

HTML5中使用json对象的实例代码

2019年07月25日  | 移动技术网IT编程  | 我要评论

下面通过实例代码给大家介绍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>
        <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>

补充:下面看下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对象
                                   txtjson.value=jsonstr2;
                           }

总结

以上所述是小编给大家介绍的html5中使用json对象的实例代码,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网