如何在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"}})

谢谢)

  • 你说的"数对象"是什么意思?
  • 如果响应中没有json的"结构",则很难回答。
  • 我添加了匿名回复0天
  • 现在还不清楚"数对象"是什么意思。物体是单一的东西。所以是"1"。
  • 我假设您的意思是"计算属性",这是一个副本。如果没有,请澄清你的问题。


您可以尝试以下操作:

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 ?');  
  });

  • return有什么重要的?你甚至没有利用它。
  • 要在没有回调的情况下链接,我将更新我的答案以了解
  • 不过,这似乎与这个问题没有任何关系。
  • @菲利克斯说得对!这是一个优点!-)


你可以

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作为答案。