Get length/size of json data

910 Views Asked by At

I have use the following codes to get my json data with certain nodes.

console.log(Object.keys(data.Top["person"]).length);

It is work fine in following structure of json data array:

data:{"Top":{"person":[{"A":"a","B":"b"},{"A":"a","B":"b"}]}}

However when the person only have one nodes, it always show the answer 2 to me, it should be answer 1.

data:{"Top":{"person":{"A":"a","B":"b"}}}

Is it possible to solve this error?

2

There are 2 best solutions below

1
On

length property is supported by type array.

data:{"Top":{"person":[{"A":"a","B":"b"},{"A":"a","B":"b"}]}} in case of this person is array enclosed with [ ]

Where as for data:{"Top":{"person":{"A":"a","B":"b"}}} person is just an object. Hence length is undefined for it.

If you are creating json out of string or formatting it make sure to include [ and ] for person attribute.

JSFiddle https://jsfiddle.net/d6pqnckh/

Also use JSON formatter to test JSON structure.

UPDATE Since you are not sure of JSON structure. What you could do is before accessing length of person check if it is an array or object.

if(Object.prototype.toString.call(data.Top.person) === '[object Array]')
      alert(data.Top.person.length);
      //It is an array
else 
     alert("I AM OBJECT"); //It is of an object type

Updated Fiddle: https://jsfiddle.net/wys7awuz/

To make it an array regardless https://jsfiddle.net/ofkboh6k/

 var p = data.Top.person;
 delete data.Top.person;
 data.Top.person = [];
 data.Top.person.push(p);
 alert(data.Top.person.length);

Include this in else part of condition. It will make it an array.

1
On

length works for type array.

change your JSON to

data:{"Top":{"person":[{"A":"a","B":"b"}]}}