如何在Jquery中将Json var分解为特定格式

时间:2013-11-09 04:09:54

标签: javascript jquery json

我正在从数据库中检索值并将其解析为JSON。我的JSON数据格式就像..

[{"INCOMING":"09:09:49","INETCALL":"00:14:09","ISD":"00:05:50","LOCAL":"02:38:02","STD":"01:39:28"}]

我想将这个JSON值分解为两个变量:

var toc=["INCOMING","INETCALL","ISD","LOCAL","STD"]

和另一个像这样的变量..

var callduration=["09:09:49","00:14:09","00:05:50","02:38:0","01:39:28"]

现在根据我的需要,我必须把它分成两个变量,因为我已经编写了一个for循环,但它不能正常工作。这是我的客户端代码..

$.ajax({
                type: 'GET',
                url: 'getdataduration',
                async:false,
                dataType: "text",
                success: function(data) {

                    console.log(data);
                    var dbdata=JSON.parse(data);
                    console.log(dbdata);
                    for(var i=0,len=dbdata.length;i<len;i++){
                        $.isNumeric(dbdata[i]) ?  callduration.push(dbdata[i]) :  toc.push(dbdata[i]);
                    }

                }

            });

            console.log(toc);
            console.log(callduration);

请伙计们帮助我。 提前谢谢..

2 个答案:

答案 0 :(得分:0)

这就是你如何使用它......

var data = [{"INCOMING":"09:09:49","INETCALL":"00:14:09","ISD":"00:05:50","LOCAL":"02:38:02","STD":"01:39:28"}];

console.log(data); 

console.log( data[0].INCOMING );     // 09:09:49 
console.log( data[0]['INCOMING'] );  // 09:09:49 

var keys = Object.keys(data[0]);

console.log(keys);    // ["INCOMING", "INETCALL", "ISD", "LOCAL", "STD"] 


var values = [];
var keys   = [];

$.each(data,function(i,val){
   console.log(val);     // Object {INCOMING: "09:09:49", INETCALL: "00:14:09", ISD: "00:05:50", LOCAL: "02:38:02", STD: "01:39:28"} 

   $.each(val,function(key2,val2){
      console.log(key2 + " = " + val2); 

      keys.push(key2); 
      values.push(val2); 

      // INCOMING = 09:09:49  
      // INETCALL = 00:14:09 
      // ISD = 00:05:50 
      // LOCAL = 02:38:02  
      // STD = 01:39:28  
   }); 
});

console.log(keys);     // ["INCOMING", "INETCALL", "ISD", "LOCAL", "STD"] 
console.log(values);   // ["09:09:49", "00:14:09", "00:05:50", "02:38:02", "01:39:28"] 

答案 1 :(得分:0)

你能试试吗,

 $(function(){

     var toc = [];
     var callduration =[];
     $.ajax({
         type: 'GET',
         url: 'getdataduration',
         async:false,
         dataType: "text",
         success: function(data) {
          //   console.log(data);
             var dbdata=JSON.parse(data);
            // console.log(dbdata);                
            $.each(dbdata[0], function(key, value){
                console.log(key, value);
                toc.push(key);
                callduration.push(value)
            });                            

         }

     });

     console.log(toc);
     console.log(callduration);

 });

输出控制台:

   ["INCOMING", "INETCALL", "ISD", "LOCAL", "STD"]

   ["09:09:49", "00:14:09", "00:05:50", "02:38:02", "01:39:28"]