obtener el tamaño del objeto json


Tengo un objeto json que es devuelto por una solicitud AJAX y estoy teniendo algunos problemas con el .length porque sigue devolviendo undefined. Solo me preguntaba si lo estoy usando bien:

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

Ambos devuelven undefined aunque sean objetos válidos.

Actualización:
Muestra del objeto JSON devuelto:

{"reqStatus":true,"phones":{"one":{"number":"XXXXXXXXXX","type":"mobile"},"two":{"number":"XXXXXXXXXX","type":"mobile"}}}
Author: Programmer Bruce, 2011-07-20

7 answers

Puedes usar algo como esto

<script type="text/javascript">

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

  var count = Object.keys(myObject).length;
  console.log(count);
</script>
 428
Author: Kasun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-13 21:02:45

Su problema es que su objeto phones no tiene una propiedad length (a menos que lo defina en algún lugar del JSON que devuelva) ya que los objetos no son lo mismo que los arrays, incluso cuando se usan como arrays asociativos. Si el objeto phones fuera un array tendría una longitud. Tienes dos opciones (tal vez más).

1) Cambie su estructura JSON (suponiendo que esto sea posible) para que 'phones' se convierta en

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

(tenga en cuenta que no hay un identificador numerado de palabras para cada teléfono tal como están devuelto en una matriz indexada 0). En esta respuesta phones.length será válida.

2) Iterar a través de los objetos contenidos dentro de su objeto teléfonos y contarlos a medida que avanza, por ejemplo,

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

Si solo estás apuntando a nuevos navegadores, la opción 2 podría verse como esto

 51
Author: tomfumb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:59

Considere usar subrayado.js . Le permitirá comprobar el tamaño, es decir, así:

var data = {one : 1, two : 2, three : 3};
_.size(data);
//=> 3
_.keys(data);
//=> ["one", "two", "three"]
_.keys(data).length;
//=> 3
 27
Author: ForestierSimon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-06 10:54:13
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
 14
Author: surya handoko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-25 06:53:24

No es necesario cambiar el formato JSON.

Sustitúyase:

console.log(data.phones.length);

Con:

console.log( Object.keys( data.phones ).length ) ;
 12
Author: kkk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-20 15:03:33

Use este

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

O

//for getting length of array
 int length = jsonArray.length();
 -1
Author: Mahesh Gawhane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-02 09:11:03
$(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);
    });
});
 -5
Author: user2674838,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-05 07:14:23