js 解析 json

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,古老的榕树,5-wow.com

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