I am retrieving JSON data from a PHP file like so:
$.getJSON('fresh_posts.php',function(data){
global_save_json = data.freshcomments;
var countPosts = data.freshposts;
var howManyPosts = countPosts.length;
I need to get the length of the first main array in the object, but there is an issue.
howManyPosts is returning undefined.
The JSON object from freshposts.php looks like this:
{
"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"
}]
}
}
What is causing this?
data.freshpostsisn't an array.Object.keys(theobject).lengthmight do what you want.