Layne
Layne

Reputation: 672

How do I count json items?

How do I count the number of items in my json feed?

Abbreviated json format...

{
    "rlm1":[...],
    "rlm2":[...],
    "rlm3":[...],
    "rlm4":[...]
}

jquery...

$.getJSON("jsondata.js", function(data) {
    alert(data.length); //returns undefined, expecting 4
}

I feel like more is needed at the top of the json file. I can reformat my json file if needed.

Thanks!

Upvotes: 2

Views: 172

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190945

Try using Object.keys in a modern browser.

$.getJSON("jsondata.js", function(data) {
    alert(Object.keys(data).length);
}

In an older browser either use a polyfill or underscore's _.keys.

Upvotes: 4

Related Questions