get size of JSON object
Asked Answered
T

9

303

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:

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

They both return undefined even though they are valid objects.

Update:
Sample of the JSON object returned:

{"reqStatus":true,"phones":{"one":{"number":"XXXXXXXXXX","type":"mobile"},"two":{"number":"XXXXXXXXXX","type":"mobile"}}}
Techno answered 20/7, 2011 at 1:44 Comment(3)
Can you post a sample of the JSON returned?Wiry
I'm not sure, wasn't me. I think your question is fine, as well.Wiry
To those came here via Google: Try solutions given below but check spellings also before that. In my case I was writing .lenght instead of .length and typescript interpreter never complained. Welcome to scripting world!Disendow
F
709

You can use something like this

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

var count = Object.keys(myObject).length;
console.log(count);
Fumble answered 17/1, 2013 at 12:49 Comment(4)
@Matt, It is NOT compulsory for every code to work in IE 7 or 8. These inadequate or non standard platforms being protected are simply drawbacks.Huey
@OlofuMark not everyone gets to choose which browser they're using (e.g. locked-down networks, versioned IE DLLs dependencies used by in-house applications). If accommodating outdated browsers requires significant effort then ignoring them can be justified, but in such a trivial case as this it's just rude not toSwithin
@OlofuMark While it is not required to support those versions, developers should know when code they produce will not work on certain versions so that they can decide whether to take that into account or not.Loyal
it's a fantastic solution to get length of json objectsLeatherleaf
S
55

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

    "phones":[{"number":"XXXXXXXXXX","type":"mobile"},{"number":"XXXXXXXXXX","type":"mobile"}]
    

    (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)) {
        count++;
      }
    }
    

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

Swithin answered 20/7, 2011 at 2:21 Comment(1)
How would I get the length of the of the JSON object with the first solution given that my JSON object is stored in a variable called jsonObject and I have the same JSON as above: "phones":[{"number":"XXXXXXXXXX","type":"mobile"},{"number":"XXXXXXXXXX","type":"mobile"}]Mayce
N
36

you dont need to change your JSON format.

replace:

console.log(data.phones.length);

with:

console.log( Object.keys( data.phones ).length ) ;
Nutmeg answered 20/1, 2016 at 15:3 Comment(0)
L
30

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

var data = {one : 1, two : 2, three : 3};
_.size(data);
//=> 3
_.keys(data);
//=> ["one", "two", "three"]
_.keys(data).length;
//=> 3
Lazurite answered 6/3, 2013 at 10:54 Comment(0)
P
19
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
Pay answered 25/3, 2015 at 6:53 Comment(1)
This is an already parsed json object. If you execute the above statements, it will give you an error 'Unexpected token o in Json'. For calculating the length of json you can directly do var length= Object.keys(json).length.Gopherwood
L
5

try this

$.parseJSON(data).length
Lactobacillus answered 14/1, 2019 at 5:37 Comment(0)
E
2

use this one

Object.keys(jsonObject).length

Earflap answered 2/6, 2016 at 9:11 Comment(2)
length() is not a JSON object funtionDelectation
@SundingWei maybe you shouldn't put parentheses --- just .length instead of .length().Slip
P
0

var data = {"reqStatus":true,"phones":{"one":{"number":"XXXXXXXXXX","type":"mobile"},"two":{"number":"XXXXXXXXXX","type":"mobile"}}}

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

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

console.log(Object.keys(data.phones.two).length);
Pectinate answered 20/5, 2023 at 5:49 Comment(0)
E
-9
$(document).ready(function () {
    $('#count_my_data').click(function () {
        var count = 0;
        while (true) {
             try {
                var v1 = mydata[count].TechnologyId.toString();
                count = count + 1;
            }
            catch (e)
            { break; }
        }
        alert(count);
    });
});
Evangelinaevangeline answered 16/8, 2013 at 12:39 Comment(2)
waiting for an exception to tell you your list has run out of elements is a bad idea, and this approach will silently give the wrong count if any element (even the last) is missing the TechnologyId propertySwithin
This code is so bad, that I am not even gonna comment further. Voted -1!Principally

© 2022 - 2024 — McMap. All rights reserved.