首页 > Web开发 > 详细

js 解析 json

时间:2014-08-19 12:52:04      阅读:312      评论:0      收藏:0      [点我收藏+]

1.简单的json格式

{
"user":
[
{
"name":"name1",
"age":24,
"sex":"男"
},
{
"name":"name2",
"age":24,
"sex":"男"
},
{
"name":"name3",
"age":24,
"sex":"男"
}
]
}

 2.完整的Ajax调用

<script type="text/javascript">

        function GetMessageByUrl() {
            $.ajax({
                type: "GET",
                cache: "false",
                //                url: "http://192.168.1.132:890/api/vehicle/tracking",
                url: "TextJson.txt",
                datatype: "json",
                success: function (data) {

                    ///
                    ///通过eval()将json格式字符串转换成json对象。
                    ///
                    var dataEval = eval("(" + data + ")");
                    alert(dataEval.user[1].name);
                    alert("节点1");

                    ///
                    ///通过$.parseJSON()将json格式字符串转换成json对象。
                    ///
                    var dataObj = jQuery.parseJSON(data);
                    alert(dataObj.user[2].name);
                    alert("节点2");

                    ///
                    ///遍历json对象中的元素
                    ///
                    $.each(dataObj.user, function (idx, item) {

                        alert("name:" + item.name + ",value:" + item.age);
                    })


                },
                error: function (err_data) {
                    alert(err_data);
                }
            })
        };


    </script>

 3.简单调用

                        var txt = ‘{"employees":[‘ +
            ‘{"firstName":"Bill","lastName":"Gates" },‘ +
            ‘{"firstName":"George","lastName":"Bush" },‘ +
            ‘{"firstName":"Thomas","lastName":"Carter" }]}‘;


                        var obj = eval("(" + txt + ")");

                        document.getElementById("fname").innerHTML = obj.employees[1].firstName
                        document.getElementById("lname").innerHTML = obj.employees[1].lastName
                        $.each(obj.employees, function (idx, item) {
                            if (idx == 0) {
                                return true; //同countinue,返回false同break 
                            }

                            alert("name:" + item.firstName + ",value:" + item.lastName);

                        });

 

js 解析 json,布布扣,bubuko.com

js 解析 json

原文:http://www.cnblogs.com/nidakun/p/3921740.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!