tirenweb
tirenweb

Reputation: 31709

How to know the number of key/value pairs in a JSON response?

I have this lines at my ajax request:

      success: function (response) {
        var result = $.parseJSON(response);

Since the response is an array of key/value pairs, how to know the number of pairs?

Upvotes: 1

Views: 1167

Answers (3)

rxjmx
rxjmx

Reputation: 2183

If it's an Array like Object you can use the following:

console.log(Object.keys(result).length)

If it's just an Array you can use:

console.log(result.length);

Upvotes: 2

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

Try this way because .length only works with array not with object. so

var count = 0;
for(var key in json)
    if(json.hasOwnProperty(key))
        count++;
alert(count);

N.B: if it is an array then go with .length alert(result.length);

Upvotes: 0

taxicala
taxicala

Reputation: 21759

You have to use length for that:

console.log(result.length);

Upvotes: 1

Related Questions