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.