如何在javascript中计算json对象

How to count json object in javascript

本问题已经有最佳答案,请猛点这里访问。

我如何计算我请求的对象?

我使用Ajax并向该URL请求JSON数据pbxApi+"/conference/participants/"+circle+"/"+data.conference+"/"+data.uniqueid+'?jsonp=response';,我想计算响应的对象。

这是我的密码

1
2
3
4
 var uri = pbxApi+"/conference/participants/"+circle+"/"+data.conference+"/"+data.uniqueid+'?jsonp=response';
        getJsonData(uri, function(res){
            console.log(res.length);
});

这是我的功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
  var getJsonData = function(uri,callback){
    $.ajax({
      type:"GET",
      dataType:"jsonp",
      url: uri,
      jsonpCallback: 'response',
      cache: false,
      contentType:"application/json",
      success: function(json){
        callback(json);
      }
    });
  }

这是我的回应

1
response({"_id":"561713a78693609968e3bbdd","event":"ConfbridgeJoin","channel":"SIP/192.168.236.15-00000024","uniqueid":"1444352918.94","conference":"0090000293","calleridnum":"0090000288","calleridname":"0090000288","__v":0,"status":false,"sipSetting":{"accountcode":"0302130000","accountcode_naisen":"201","extentype":0,"extenrealname":"UID1","name":"0090000288","secret":"Myojyo42_f","username":"0090000288","context":"innercall_xdigit","gid":101,"cid":"0090000018"}})

谢谢)


您可以尝试以下操作:

1
Object.keys(jsonArray).length;

获取JSON对象中的项目数。

另请参阅object.keys

Object.keys() returns an array whose elements are strings
corresponding to the enumerable properties found directly upon object.
The ordering of the properties is the same as that given by looping
over the properties of the object manually.


一种解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 var uri = pbxApi+"/conference/participants/"+circle+"/"+data.conference+"/"+data.uniqueid+'?jsonp=response';

var getJsonData = function(uri,callback){
    return $.ajax({ // <----- note the return !
      type:"GET",
      dataType:"jsonp",
      url: uri,
      jsonpCallback: 'response',
      cache: false,
      contentType:"application/json",
      success: function(json){
        if(callback) callback(json);
      }
    });
  }

getJsonData(uri, function(res){
  console.log( Objec.keys(res).length) );
});

// with the return you will be able to do :
getJsonData(uri)
  .done( function(res){
    console.log( Objec.keys(res).length) );
  })
  .error(function( err ){
     console.log('an error ?? what is it possible ?');  
  });


你可以

1
2
3
4
success: function(json){
    console.log('Object keys length: ' + Object.keys(json).length)
    callback(json);
}

例如,{a:1, b:2, c:'Batman'}给出3作为答案。