Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count Key/Values in JSON [duplicate]

Tags:

Possible Duplicate:
Length of Javascript Associative Array

I have a JSON that looks like this:

Object:    www.website1.com : "dogs"    www.website2.com : "cats"    >__proto__ : Object 

This prints when I do this:

console.log(obj); 

I am trying to get the count of the items inside this JSON, obj.length returns "undefined" and obj[0].length returns

Uncaught TypeError: Cannot read property 'length' of undefined

I would expect a length to return "2" in this case. How can I find the count?

Thanks!

like image 598
Doug Molineux Avatar asked Jun 08 '11 18:06

Doug Molineux


People also ask

How do I count the number of keys in JSON?

To count the number key/value pairs in a JSON object we need to convert an array. And then we can easily count the number of element in the array which is same as the number key value pairs in the json object. Object.

Can JSON contain duplicate keys?

JSON with duplicate key entries have to be handled either by ignoring the duplicate entries or by throwing an exception. Until Mule Runtimes 3.8. 6/3.9. 0, JSON Schema Validator handles them by retaining the last duplicate entry and not throwing an exception.

Does JSON syntax allow duplicate keys in an object?

The names within an object SHOULD be unique. If a key is duplicated, a parser SHOULD reject. If it does not reject, it MUST take only the last of the duplicated key pairs.


1 Answers

You have to count them yourself:

function count(obj) {    var count=0;    for(var prop in obj) {       if (obj.hasOwnProperty(prop)) {          ++count;       }    }    return count; } 

Although now that I saw the first comment on the question, there is a much nicer answer on that page. One-liner, probably just as fast if not faster:

function count(obj) { return Object.keys(obj).length; } 

Be aware though, support for Object.keys() doesn't seem cross-browser just yet.

like image 77
davin Avatar answered Oct 14 '22 23:10

davin