I'm working with some Json that is similar to:
{
"Apps" : [
{
"Name" : "app1",
"id" : "1",
"groups" : [
{ "id" : "1", "name" : "test group 1", "desc" : "this is a test group" },
{ "id" : "2", "name" : "test group 2", "desc" : "this is another test group" }
]
}
]
}
If I parse it in jquery to return an object and I'm iterating through the apps like so:
$.each(myJsonObject.Apps, function() { ... };
How can I get the length of this.groups
?
I've tried
and I cannot find any decent documentation on multiple tier json objects that have good information.
Any links or examples or suggestions would be appreciated.
To obtain the size of a JSON-encoded array or object, use the json_size function, and specify the column containing the JSON string and the JSONPath expression to the array or object.
In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.
' { } ' used for Object and ' [] ' is used for Array in json.
Try:
$.each(myJsonObject.Apps, function(i, obj) { ... });
obj.Groups.length;
Javascript is case sensitive. Change this.Groups.length
to this.groups.length
.
This code should work:
$.each(myJsonObject.Apps, function() {
alert(this.groups.length);
});
I have a working example on JSFiddle
To avoid this sort of problem, you should use a consistent capitalization. In Javascript, it is conventional to use camelCase.
this works well:
HTML:
<span id="result"></span>
JS:
var myJsonObject =
{
"Apps" : [
{
"Name" : "app1",
"id" : "1",
"groups" : [
{ "id" : "1", "name" : "test group 1", "desc" : "this is a test group" },
{ "id" : "2", "name" : "test group 2", "desc" : "this is another test group" }
]
}
]
};
$.each(myJsonObject.Apps, function(i, el) {
$("#result").html(el.groups.length);
});
example
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