首页 > 代码库 > jQuery遍历多层json数据

jQuery遍历多层json数据

 

1、json与jsonp的区别(待查)

 

2、要遍历的数据如下:

{"status": "ok", "code": 200, "data": {"343946": {"8144": {"feed": 0, "instagram": 0, "livefyre": 21, "facebook": 0, "total": 21, "twitter": 0}}, "343945": {"2649": {"feed": 0, "instagram": 0, "livefyre": 42, "facebook": 0, "total": 42, "twitter": 0}}}}

3、数据来源:
https://coxnews.bootstrap.fyre.co/api/v1.1/public/comments/ncomments/MzQzOTQ1OjI2NDl8MzQzOTQ2OjgxNDQ==.json

4、代码如下:

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script type="text/javascript" src="http://www.mamicode.com/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
            //$.each( [4,1,2], function(i, n){
            //    alert( "Item #" + i + ": " + n );
            //});
            //$.each( { name: "John", lang: "JS" }, function(i, n){
            //    alert( "Name: " + i + ", Value: " + n );
            //});
                $.ajax({
                    dataType: ‘jsonp‘,
                    url: ‘https://coxnews.bootstrap.fyre.co/api/v1.1/public/comments/ncomments/MzQzOTQ1OjI2NDl8MzQzOTQ2OjgxNDQ==.json‘,
                    success: function(data) {
                        var dataObj = eval(data).data;
                        //一层循环
                        $.each(dataObj, function(n1, value) {
                            alert(n1);
                                //二层循环
                                $.each(value,function(n2,value1){
                                    alert(n2);

                                   //三层循环
                                        $.each(value1,function(n3,value2){
                                            alert(n3);
                                            alert(value2);
                                        });
                                });
                           
                            //for (var i = 0; i < value.length; i++) {
                            //    alert(value[i]);
                           // }
                        });
                    }
                });
            }
            );
        </script>
    </head>
    <body>
        <div>TODO write content</div>
    </body>
</html>

jQuery遍历多层json数据