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:06
$(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);
    });
});
查看更多
我想做一个坏孩纸
3楼-- · 2020-01-24 19:16

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
查看更多
放荡不羁爱自由
4楼-- · 2020-01-24 19:16

try this

$.parseJSON(data).length
查看更多
Rolldiameter
5楼-- · 2020-01-24 19:17

You can use something like this

<script type="text/javascript">

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

  var count = Object.keys(myObject).length;
  console.log(count);
</script>
查看更多
劫难
6楼-- · 2020-01-24 19:17
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
查看更多
We Are One
7楼-- · 2020-01-24 19:20

you dont need to change your JSON format.

replace:

console.log(data.phones.length);

with:

console.log( Object.keys( data.phones ).length ) ;
查看更多
登录 后发表回答