Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  95] [ 2]  / answers: 1 / hits: 25367  / 12 Years ago, fri, may 18, 2012, 12:00:00

I have following Jsonstring



  var j = { name: John };
alert(j.length);


it alerts : undefined, How can i find the length of json Array object??



Thanks


More From » json

 Answers
24

Lets start with the json string:



var jsonString = '{name:John}';


you can easily determine its length:



alert(The string has +jsonString.length+ characters); // will alert 15


Then parse it to an object:



var jsonObject = JSON.parse(jsonString);


A JavaScript Object is not an Array and has no length. If you want to know how many properties it has, you will need to count them:



var propertyNames = Object.keys(jsonObject);
alert(There are +propertyNames.length+ properties in the object); // will alert 1


If Object.keys, the function to get an Array with the (own) property names from an Object, is not available in your environment (older browsers etc.), you will need to count manually:



var props = 0;
for (var key in jsonObject) {
// if (j.hasOwnProperty(k))
/* is only needed when your object would inherit other enumerable
properties from a prototype object */
props++;
}
alert(Iterated over +props+ properties); // will alert 1

[#85505] Wednesday, May 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nathalieg

Total Points: 462
Total Questions: 106
Total Answers: 93

Location: Turks and Caicos Islands
Member since Tue, Mar 30, 2021
3 Years ago
;