JSON - json解析实例

JSON用法

<!doctype html>
<html>
    <head>
        <title>JSON用法</title>
        <meta charset="utf-8" />
        <script>
            window.onload=function(){
                //定义一个JSON对象,用来存储用户信息,属性为string类型,值为任意类型
                var person={"name":"张三","age":24,"height":180.5,"wife":null};
                document.getElementById(‘info1‘).innerHTML="姓名:"+person.name+",年龄:"+person.age+",身高:"+person.height+",媳妇:"+person.wife;

                //定义一个user对象
                var user={
                    "name":{"first":"tom","last":"cruise"},
                    "age":25,
                    "address":{
                        "province":"江苏省",
                        "city":"南京市",
                        "district":"秦淮区",
                        "street":"龙蟠中路"},
                    "hobby":"吃饭"    
                };
                document.getElementById("info2").innerHTML="姓:"+user.name.last+",名:"+user.name.first+",街道:"+user.address.street+",爱好:"+user.hobby;

                //定义一个字符串数组
                /*var names=new Array();
                names[0]="tom";
                names[1]="jack";
                names[2]="alice";*/
                //var names=new Array("tom","jack","alice");
                var names=["tom","jack","alice"];
                for(var i=0;i<names.length;i++){
                    //alert(names[i]);
                }

                //定义一个JSON对象数组,存储多个学生信息
                var users=[{"name":"张敬浩","age":25,"sex":"女","address":"珠江路"},
                            {"name":"王照陆","age":22,"sex":"男","address":"龙蟠中路"},
                            {"name":"唐伯虎","age":26,"sex":"男","address":"山西路"}];
                for(var i=0;i<users.length;i++){
                    document.getElementById("info3").innerHTML+=users[i].name+","+users[i].age+","+users[i].address+"<br/>"
                }

                //将JSON转换为字符串
                var student={"name":"张三","age":24,"height":180.5,"wife":null};
                var str=JSON.stringify(student);
                //alert(str);

                //将字符串转换为JSON
                var str2=‘{"name":"tom","age":23}‘;
                var json=JSON.parse(str2);
                //alert(json.name);

                //将字符串转换为JSON数组
                var str3=‘[{"name":"张敬浩","age":25,"sex":"女","address":"珠江路"},{"name":"王照陆","age":22,"sex":"男","address":"龙蟠中路"},{"name":"唐伯虎","age":26,"sex":"男","address":"山西路"}]‘;
                var json2=JSON.parse(str3);
                alert(json2[1].name);

            }
        </script>
    </head>
    <body>
        <div id="info1"></div>
        <div id="info2"></div>
        <div id="info3"></div>
    </body>
</html> 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。