JSON数组长度

时间:2014-12-18 08:14:43

标签: javascript json

这是我的JSON数组代码

var App = [
 {
   "id": "123",
   "caption": "Test",
   "description": "Test Desc"
 },
 {
   "id": "345",
   "caption": "adsasdasd",
   "description": ""
 },
 {
   "id": "456",
   "caption": "adsasdasd",
   "description": ""
 },
 {
   "id": "578",
   "caption": "adsasdasd",
   "description": ""
 }
]

我尝试使用以下代码

var obj = $.parseJSON(App);
alert(JSON.stringify(obj,4,null));
var AppLen = obj[i].length;
alert(AppLen);

但我没有得到任何解决方案。如果我错过任何获取JSON对象数组长度的东西,请告诉我。

2 个答案:

答案 0 :(得分:1)

您的数据已经是json格式:这样做

var App = [
           {
             "id": "123",
             "caption": "Test",
             "description": "Test Desc"
           },
           {
             "id": "345",
             "caption": "adsasdasd",
             "description": ""
           },
           {
             "id": "456",
             "caption": "adsasdasd",
             "description": ""
           },
           {
             "id": "578",
             "caption": "adsasdasd",
             "description": ""
           }
          ];

console.log(App);
console.log(App[0].length);// you can not get length from this because it is not array it's an object now.

var AppLen = App.length;
alert(AppLen);

答案 1 :(得分:-1)

obj.size() or obj.length

如果不运行,请尝试:Length of a JavaScript object

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

// Get the size of an object
var size = Object.size(myArray);