代码改变世界

js-json数据

2020-04-02 12:42  默默不语  阅读(183)  评论(0编辑  收藏  举报
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script type="text/javascript">
            function User(name,age){
                this.name = name;
                this.age = age;
            }
            var u1 = new User("张三",18);
            var u2 = new User("李四",20);
            document.write("默认输入格式:"+u1.name+" "+u1.age+"<br>");
            var str = JSON.stringify(u1);
            document.write("json格式:"+str+"<br>");
            var arr1 = new Array();
            arr1[0] = u1;
            document.write("json格式-数组:"+JSON.stringify(arr1)+"<br>");
            
            /* json串转对象 */
            /* 此处要用单引号 */
            var str = '{"name":"张三","age":18}';
            var u3 = JSON.parse(str);
            document.write("json格式转对象:"+u3.name+"<br>");
            
            var str1 = '[{"name":"张三","age":18},{"name":"lisi","age":15},{"name":"wangwu","age":19}]';
            var userArray = JSON.parse(str1);
            document.write("userArray长度:"+userArray.length+"<br>");
        </script>
    </head>
    <body>
    </body>
</html>