Possible Duplicate: Length of a JavaScript object (that is, associative array)
I have JSON in the following format
[{"student":{"name" : "ABCD",
"age":8,
}
"user":{ "firstName":"ABCD",
"age": 9,
}
},
{"student":{"name" : "XCYS",
"age":10,
}
"user":{ "firstName":"GGG",
"age": 11,
}
},]
I tried using (data.student[i].length)
, which did not work (just to see what the length of the object is), and I also tried (data.user[i])
to no avail.
I am basically very confused on how I can get the length of one of the objects in the JSON and how I can effectively display it. How can I do this?
The content in your questions doesn't parse as valid JSON as all keys need to be wrapped in quotes (so you should have "age": 11
instead of age: 11
). All key/value pairs in an object should be separated by a comma (so you should have "firstName": "GGG", "age": 11
instead of "firstName": "GGG" "age": 11
. You also have a trailing comma in the outer array.
So long as you have valid JSON, you should be able to use JSON.parse(data)
in all browsers newer than IE7 to convert the string into an actual object. Once parsed into an object, you can use:
var data = "your JSON string";
var object = JSON.parse(data);
console.log(object.length); // the number of objects in the array
console.log(object[0].student.name; // the name of the first student
If you are supporting browsers IE7 and older, check out Douglas Crockford's JSON polyfill: https://github.com/douglascrockford/JSON-js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With