Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json Object Array Length

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

  • this.groups.length
  • this.groups.length()
  • $(this).groups.length()

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.

like image 200
Patrick Avatar asked Apr 07 '11 19:04

Patrick


People also ask

How do you find the length of a JSON object array?

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.

Can a JSON object contain an array?

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.

What is [] and {} in JSON?

' { } ' used for Object and ' [] ' is used for Array in json.


3 Answers

Try:

$.each(myJsonObject.Apps, function(i, obj) { ... });

obj.Groups.length;
like image 121
mattsven Avatar answered Oct 05 '22 23:10

mattsven


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.

like image 20
Peter Olson Avatar answered Oct 05 '22 22:10

Peter Olson


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

like image 45
andres descalzo Avatar answered Oct 05 '22 22:10

andres descalzo