get size of json object

2020-01-24 18:27发布

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"}}}

8条回答
混吃等死
2楼-- · 2020-01-24 19:22

use this one

//for getting length of object
 int length = jsonObject.length();

or

//for getting length of array
 int length = jsonArray.length();
查看更多
Ridiculous、
3楼-- · 2020-01-24 19:31

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

查看更多
登录 后发表回答