get size of json object

get size of json object

i have a json object that gets returned by an AJAX request and I am having some trouble with the .length because it keeps returning undefined. Just wondering if I’m using it right:

They both return undefined even though they are valid objects.
Sample of the JSON object returned:


Solution 1:

You can use something like this

<script type="text/javascript">

  var myObject = {'name':'Kasun', 'address':'columbo','age': '29'}

  var count = Object.keys(myObject).length;

Solution 2:

Your problem is that your phones object doesn’t have a length property (unless you define it somewhere in the JSON that you return) as objects aren’t the same as arrays, even when used as associative arrays. If the phones object was an array it would have a length. You have two options (maybe more).

  1. Change your JSON structure (assuming this is possible) so that ‘phones’ becomes


    (note there is no word-numbered identifier for each phone as they are returned in a 0-indexed array). In this response phones.length will be valid.

  2. Iterate through the objects contained within your phones object and count them as you go, e.g.

    var key, count = 0;
    for(key in data.phones) {
      if(data.phones.hasOwnProperty(key)) {

If you’re only targeting new browsers option 2 could look like this

Related:  Javascript closures vs PHP closures, what's the difference?

Solution 3:

Consider using underscore.js. It will allow you to check the size i.e. like that:

var data = {one : 1, two : 2, three : 3};
//=> 3
//=> ["one", "two", "three"]
//=> 3

Solution 4:

you dont need to change your JSON format.




console.log( Object.keys( data.phones ).length ) ;

Solution 5:

var json=[{"id":"431","code":"0.85.PSFR01215","price":"2457.77","volume":"23.0","total":"565.29"},{"id":"430","code":"0.85.PSFR00608","price":"1752.45","volume":"4.0","total":"70.1"},{"id":"429","code":"0.84.SMAB00060","price":"4147.5","volume":"2.0","total":"82.95"},{"id":"428","code":"0.84.SMAB00050","price":"4077.5","volume":"3.0","total":"122.32"}] 
var obj = JSON.parse(json);
var length = Object.keys(obj).length; //you get length json result 4

Solution 6:

try this