在jQuery中解析Json多维数组

时间:2014-02-07 22:11:55

标签: javascript jquery json

我正在尝试解析具有嵌套数组的facebook json文件中的文本,但我只得到第一级数组的元素。 我想从嵌套数组中获取数据(如果存在)。 例如,使用上面的代码,我无法获得数组“category_list”中的字段。

数据示例

{
"userdata": [
        {
          "category": "Community",
          "name": "whitespace",
          "created_time": "2014-01-30T13:58:22+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "City",
          "category_list": [
            {
              "id": "xxxxxxxxxxxxxxxxxx",
              "name": "City"
            }
          ],
          "name": "Marburg, Queensland",
          "created_time": "2014-01-09T13:09:14+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "Hotel",
          "name": "Hotel Line",
          "created_time": "2014-01-06T20:41:44+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "Food/beverages",
          "name": "Olive",
          "created_time": "2014-01-06T20:41:16+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "Education",
          "name": "Genius Solutions Group",
          "created_time": "2014-01-06T20:40:48+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "Hotel",
          "category_list": [
            {
              "id": "128232937246338",
              "name": "Travel & Transportation"
            }
          ],
          "name": "Seabreeze",
          "created_time": "2014-01-06T20:40:07+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "Local business",
          "category_list": [
            {
              "id": "xxxxxxxxxxxxxxxxxx",
              "name": "Computer Store"
            }
          ],
          "name": "Project",
          "created_time": "2014-01-06T20:38:26+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "Tv show",
          "name": "helloooo",
          "created_time": "2014-01-06T20:38:08+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        }
      ]
}     

我使用的代码是

<html>
<head>
<title>Parsing</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript">
</script>
 </head>
 <body>
<a href="#" id="loaduserdata">User Data</a>
<table id="userdata" border="1">
    <thead>


    </thead>
    <tbody></tbody>
</table>
<script>
$(document).ready(function(){
});
$("#loaduserdata").click(function(){
    $("#userdata tbody").html("");
    $.getJSON(
        "jsondata.php",
        function(data){
            $.each(data.userdata, function(i,user){
                var tblRow =
                    "<tr>"
                    +"<td>"+user.category+"</td>"
                    +"<td>"+user.name+"</td>"
                    +"</tr>"
                $(tblRow).appendTo("#userdata tbody");
            });
        }
    );
});
</script>
 </body>
 </html>

,结果

User Data
+----------------+------------------------+
| Community      | whitespace             |
| City           | Marburg, Queensland    |
| Hotel          | Hotel Line             |
| Food/beverages | Olive                  |
| Education      | Genius Solutions Group |
| Hotel          | Seabreeze              |
| Local business | Project                |
| Tv show        | helloooo               |
+----------------+------------------------+

请帮助一下......

2 个答案:

答案 0 :(得分:1)

一个简单的解决方案就是在表格中添加以逗号分隔的类别列表。使用map然后join

+ "<td>" + user.category_list.map(function(item) { return item.name; }).join(", ") + "</td>"

当然,您还必须检查“category_list”是否存在,但这并不难:

+ "<td>" + (typeof user.category_list == "undefined" ? "" :
        user.category_list.map(function(item) { return item.name; }).join(", "))
+ "</td>"

Fiddle

答案 1 :(得分:0)

属性category_list是一个数组,需要一个嵌套循环。

查看小提琴以获取更新的显示:http://jsfiddle.net/4gK5L/3/

 $(document).ready(function() {
            (function(){
                $.each(data.userdata, function (i, user) {
                    var hasData = (typeof (user.category_list) != 'undefined' && user.category_list.length > 0);
                    var i = 0;
                    var tblRow = '<h1>' + user.category + '</h1><ul>';
                    tblRow = tblRow + '<li>' + user.name + '</li>'
                    // + ' '  + user.Name + '
                    if (hasData)
                    {
                        tblRow = tblRow + '<li>Subcategory Info:<ul>'
                        while(i < user.category_list.length){
                             tblRow = tblRow + '<li>Sub Category Id: ' + user.category_list[i].id + '</li><li>Sub Category Name: ' + user.category_list[i].name + '</li>'
                            i++
                        }
                        tblRow = tblRow + '</ul></li>';
                    }
                    var dateTime = new Date(user.created_time);
                    var createdDate = (dateTime.getMonth() + 1) + '-' + dateTime.getDate() + '-' + dateTime.getFullYear();
                    tblRow = tblRow + '<li>Created: ' + createdDate + '</li>'
                    tblRow = tblRow + '<li>Category Id: ' + user.id + '</li>'
                    tblRow = tblRow + '</ul>';
                    $(tblRow).appendTo("#userdata");
                });
            })();
        });

顺便说一句,McGarnagle的答案比我的更优雅,如果你使用它,你应该接受他的答案。