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?
lengthproperty is supported by type array.data:{"Top":{"person":[{"A":"a","B":"b"},{"A":"a","B":"b"}]}}in case of thispersonis array enclosed with[ ]Where as for
data:{"Top":{"person":{"A":"a","B":"b"}}}personis just an object. Hencelengthisundefinedfor it.If you are creating json out of string or formatting it make sure to include
[and]forpersonattribute.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
personcheck if it is an array or object.Updated Fiddle: https://jsfiddle.net/wys7awuz/
To make it an array regardless https://jsfiddle.net/ofkboh6k/
Include this in else part of condition. It will make it an array.