The size of a JSON array is the number of elements. As JSON arrays are zero terminated, the size of a JSON array is always the last index + 1.
How large can JSON Documents be? One of the more frequently asked questions about the native JSON data type, is what size can a JSON document be. The short answer is that the maximum size is 1GB. However, JSON often changes how data modeling is done, and deserves a slightly longer response.
You can get the number of elements in an array using yourArray. length .
You can use something like this
var myObject = {'name':'Kasun', 'address':'columbo','age': '29'}
var count = Object.keys(myObject).length;
console.log(count);
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).
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.
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
you dont need to change your JSON format.
replace:
console.log(data.phones.length);
with:
console.log( Object.keys( data.phones ).length ) ;
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With