歡迎來到DIVCSS5查找CSS資料與學習DIV CSS布局技術!

 下面通過實例代碼給大家介紹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;
                           }

如需轉載,請注明文章出處和來源網址:http://www.khijtf.live/wenji/w50975.shtml

江西多乐彩走势图今天