coder
coder

Reputation: 1892

How can i find the length of this Json object

I want to find the length of this JSON object so any one tell me how can i get length of the JSON object...means i want to know how many data this json object contain.

var ddData = [{ "01":"United States",
                "02":"United Kingdom",
                "03":"Aruba",
                "04":"United Kingdom",
                "05":"Aruba",
                "06":"Bahrain",
                "07":"United Kingdom",
                "08":"Algeria",
                "09":"Andorra",
                "10":"American Samoa",
                "11":"United States"
             }]

Upvotes: 3

Views: 7825

Answers (6)

BalaKrishnan웃
BalaKrishnan웃

Reputation: 4557

You can use the Object.keys that will return the length of specified collection.JS Fiddle.

(Browser support from here) (Doc on Object.keys here, includes method you can add to non-ECMA5 browsers)

Upvotes: 4

Pranav 웃
Pranav 웃

Reputation: 8477

You could use Object.keys method to get the object keys.
Since ddData is an array, and the first index contains an object, you could do this :

Object.keys(ddData[0]).length;

However, Object.keys does not work on old browsers.

For that, you could iterate through the object and increment a variable to get the length of that object.

var count = 0;
for(var i in ddData[0]) {
    count++;
}

Upvotes: 12

coder
coder

Reputation: 1892

Now i got the answer....

var Data = { "01":"United States",
            "02":"United Kingdom",
            "03":"Aruba",
            "04":"United Kingdom",
            "05":"Aruba",
            "06":"Bahrain",
            "07":"United Kingdom",
            "08":"Algeria",
            "09":"Andorra",
            "10":"American Samoa",
            "11":"United States"
         }

var count = 0;
for(x in Data){
    count++;
}
console.log('cnt',count)

Upvotes: 1

Arun Killu
Arun Killu

Reputation: 14233

var json = JSON.parse(ddData);
for(i=0;i<json.length;i++)
{
alert(json[i].length);
}

Upvotes: 1

Murali N
Murali N

Reputation: 3498

you can simply do this instead of calling functions

var key, count = 0;
for(key in ddData[0]) {
  count++;
}

console.log(count + " is size of the json");

Upvotes: 2

Zhou Lee
Zhou Lee

Reputation: 96

var length=0;
for(attr in ddData[0]){
     length++;
}

Upvotes: 1

Related Questions