2011-04-07 116 views
9

我與一些Json的工作類似於:JSON對象數組的長度

{ 
    "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" } 
    ] 
    } 
    ] 
} 

如果我解析它在jQuery中返回一個對象,我通過應用程序,像這樣的迭代:

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

我怎樣才能得到this.groups的長度?

我已經試過

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

和我在多層JSON對象中找不到任何有好信息的文檔。

任何鏈接或示例或建議,將不勝感激。

+2

是不是隻是一個錯字? JSON中的'groups'全部爲小寫,但代碼示例具有'Groups'。 – 2011-04-07 19:56:45

+0

即使在正確的情況下它也不起作用。生病更新我的例子 – Patrick 2011-04-07 19:58:39

+0

你確定嗎?當我在控制檯中試用它時,它工作正常。 – 2011-04-07 20:01:47

回答

19

嘗試:

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

obj.Groups.length; 
+0

奇怪,它不工作時,我引用此...但如果我引用myJsonObject它的作品。一旦限制到期>「不適用」 – Patrick 2011-04-07 20:04:25

0

看起來你只是在你的代碼中有一個簡單的錯字。 JavaScript區分大小寫,因此groups而不是Groups相同。

如果您的JSON對象具有全部小寫的groups,就像您的示例一樣,那麼您只需在迭代函數內部使用this.groups.length

4

JavaScript是區分大小寫的。將this.Groups.length更改爲this.groups.length

此代碼應工作:

$.each(myJsonObject.Apps, function() { 
    alert(this.groups.length); 
}); 

我有JSFiddle

爲了避免這種問題工作的例子,你應該使用一致的大小寫。在Javascript中,傳統使用camelCase。

2

這個效果很好:

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

0

試試這個: 功能objectCount(OBJ){

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

其中obj是使用JSON數組作爲子對象

0

JSON對象試試這個

import org.json.JSONObject; 

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