开发者

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 mu开发者_JAVA技巧ltiple tier json objects that have good information.

Any links or examples or suggestions would be appreciated.


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


Looks like you just have a simple typo in your code. JavaScript is case-sensitive, so groups is not the same as Groups.

If your JSON object has groups in all lowercase, like your example, then you only need to use this.groups.length inside the iteration function.


Try this: function objectCount(obj) {

objectcount = 0;
$.each(obj, function(index, item) {
    objectcount = objectcount + item.length;
});
return objectcount;
}
objectCount(obj);

where obj is a json object with json array as sub objects


Try this

import org.json.JSONObject;

JSONObject myJsonObject = new JSONObject(yourJson);
int length = myJsonObject.getJSONArray("groups").length();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜