获取Json对象的长度

时间:2014-03-22 16:22:27

标签: jquery json

我有从php文件返回的json对象,json值如下

    {
  "0": {
    "id": "35",
    "name": "first name",
    "date": "2014-03-03",
    "age": "25"
  },
  "1": {
    "id": "36",
    "name": "name",
    "date": "0000-00-00",
    "age": "25"
  },
  "2": {
    "id": "37",
    "name": "myname",
    "date": "0000-00-00",
    "age": "25"
  },
  "average_age": 25,
  "count": 3
}

如何获得除average_age和count之外的其他值的计数 对于给定的json对象,我想在jQuery中获得3作为长度

4 个答案:

答案 0 :(得分:48)

我得到了答案

Object.keys(result).length // returns 5

<强>更新

根据评论,这不适用于IE 7和8

答案 1 :(得分:7)

尝试:

var count = 0;
while (obj[count]) {
    count++;
}

答案 2 :(得分:1)

要“获取除average_agecount以外的值的计数”,您可以执行以下操作:

function getCount(obj) {
    var count = 0,
        prop;

    for (prop in obj) {
        if (obj.hasOwnProperty(prop) && prop !== "average_age" && prop !== "count") {
            count += 1;
        }
    }
    return count;
}

var str = '{"0":{"id":"35","name":"Ahamed shajeer","date":"2014-03-03","age":"25"},"1":{"id":"36","name":"Meshajeer","date":"0000-00-00","age":"25"},"2":{"id":"37","name":"Iam shajeer","date":"0000-00-00","age":"25"},"average_age":25,"count":3}',
    obj = JSON.parse(str);

console.clear;
console.log(getCount(obj));

结果:

3

你不需要jQuery。无论如何,你为什么不想直接使用count字段?

答案 3 :(得分:0)

这种方式对我有用:

var jsonObject = JSON.stringify(response); var count = JSON.parse(jsonObject).length;