HTML5中应用json目标的案例编码

2021-02-23 01:00 jianzhan

下面根据案例编码给大伙儿详细介绍HTML5中应用json目标的方式,实际编码以下所示:

<!DOCTYPE html>
<html>
    <head>
     <meta charset="UTF⑻">
     <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中,我在前面的1个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 是1个 JSON目标
                                   txtJson.value=jsonStr2;
                           }

总结

以上所述是网编给大伙儿详细介绍的HTML5中应用json目标的案例编码,期待对大伙儿有一定的协助,假如大伙儿有任何疑惑请给我留言,网编会立即回应大伙儿的。在此也十分谢谢大伙儿对脚本制作之家网站的适用!