1

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?

7
  • 1
    data.freshposts isn't an array. Commented Jun 9, 2015 at 21:02
  • Ah, it's an object? How would I get how many elements are in the object then? Commented Jun 9, 2015 at 21:02
  • Object.keys(theobject).length might do what you want. Commented Jun 9, 2015 at 21:02
  • What do you mean 'returning undefined'? It's a variable Commented Jun 9, 2015 at 21:03
  • 1
    Better yet, make it an array, rather than hacking around the fact that you're returning a semantically incorrect data type. Commented Jun 9, 2015 at 21:03

2 Answers 2

2

You should do something like:

$.getJSON('fresh_posts.php',function(data){
    global_save_json = data.freshcomments;
    var countPosts = Object.keys(data.freshposts).length;
});
Sign up to request clarification or add additional context in comments.

Comments

2

"freshposts" is not an array it's an object:

"freshposts": { ... }

It should look like this:

"freshposts": [ ... ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.