JSON对象中的数组长度未定义

时间:2015-06-09 20:59:22

标签: javascript jquery json

我正在从PHP文件中检索JSON数据,如下所示:

$.getJSON('fresh_posts.php',function(data){
    global_save_json = data.freshcomments;
    var countPosts = data.freshposts;
    var howManyPosts = countPosts.length;

我需要获取对象中第一个主数组的长度,但是存在问题。

howManyPosts正在返回undefined

来自freshposts.php的JSON对象如下所示:

{ 
    "freshposts":{

         // two example posts with ID 5 and 2

        "5": {
            "id":"5",
            "image":"link.jpg",
            "submitter":"4322309",
            "views":"3"
        },
        "2": {
            "id":"2",
            "image":"link.jpg",
            "submitter":"4322309",
            "views":"5"
        }
    },

    // now each comment tied to the posts

    "freshcomments":{
        "2": [{
            "id":"1",
            "submitter":"submitter",
            "time":"2435657",
            "comment":"comment",
            "score":"10",
            "postid":"2"
        },
        {
            "id":"2",
            "submitter":"submitter",
            "time":"2435657",
            "comment":"comment",
            "score":"10",
            "postid":"2"
        }
    ],
        "5": [{
            "id":"3",
            "submitter":"submitter",
            "time":"2435657",
            "comment":"comment",
            "score":"10",
            "postid":"5"
        }]
    }
}

造成这种情况的原因是什么?

2 个答案:

答案 0 :(得分:1)

" freshposts"它不是一个数组,它是一个对象:

"freshposts": { ... }

它应该是这样的:

"freshposts": [ ... ]

答案 1 :(得分:1)

您应该执行以下操作:

$.getJSON('fresh_posts.php',function(data){
    global_save_json = data.freshcomments;
    var countPosts = Object.keys(data.freshposts).length;
});