【问题标题】:Json Object Array LengthJson 对象数组长度
【发布时间】:2011-08-01 00:04:12
【问题描述】:

我正在使用一些类似于以下内容的 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()
  • $(this).groups.length()

我找不到任何关于具有良好信息的多层 json 对象的体面文档。

任何链接或示例或建议将不胜感激。

【问题讨论】:

  • 这不只是一个错字吗? JSON 中的groups 全部小写,但您的代码示例有Groups
  • 即使在正确的情况下它也不起作用。生病更新我的例子
  • 你确定吗?当我在控制台中尝试时它工作正常。
  • 试试 $(var.Apps[0].groups).length

标签: jquery arrays json


【解决方案1】:

试试:

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

obj.Groups.length;

【讨论】:

  • 奇怪,当我引用它时它不起作用......但如果我引用 myJsonObject 它会起作用。限制到期后不接受>
【解决方案2】:

Javascript 区分大小写。将this.Groups.length 更改为this.groups.length

这段代码应该可以工作:

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

我在JSFiddle 上有一个工作示例

为避免此类问题,您应该使用一致的大小写。在 Javascript 中,通常使用驼峰命名法。

【讨论】:

    【解决方案3】:

    这很好用:

    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

    【讨论】:

      【解决方案4】:

      看起来您的代码中只是有一个简单的错字。 JavaScript 区分大小写,因此groupsGroups相同。

      如果您的 JSON 对象具有全小写的groups,就像您的示例一样,那么您只需在迭代函数中使用this.groups.length

      【讨论】:

        【解决方案5】:

        试试这个: 函数 objectCount(obj) {

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

        其中 obj 是以 json 数组作为子对象的 json 对象

        【讨论】:

          【解决方案6】:

          试试这个

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-10-04
            • 1970-01-01
            • 2011-03-15
            • 2014-04-30
            • 2014-04-21
            • 2017-03-29
            • 2014-10-18
            相关资源
            最近更新 更多