当前位置 : 主页 > 网页制作 > JQuery >

jQuery解析JSON对象和数组

来源:互联网 收集:自由互联 发布时间:2021-06-15
在以下代码中: $.getJSON('?php echo $this-Html-url(array('controller'='accounts', 'action'='get_customers_order_mcs')); ?/'+customer_order_id, function(data){ var json_mc = data.MasterCarton.mc; alert(json_mc); $.each(json_mc,functio
在以下代码中:

$.getJSON('<?php echo $this->Html->url(array('controller'=>'accounts', 'action'=>'get_customers_order_mcs')); ?>/'+customer_order_id,
                function(data){
                    var json_mc = data.MasterCarton.mc;
                    alert(json_mc);
                    $.each(json_mc,function(){
                         console.log(this);
                   });
             });

作为回应发送的数据如下 –

{
     "MasterCarton":{
                         "id":"40",
                         "mc":"[
                                    "1":{\"mc_number\":\"Warehouse1\\\/2013-2014\\\/CO\\\/ABC Corp\\\/239\\\/101-Red-1\",\"config\":{\"S2\":10,\"S1\":10},\"delivered\":0},            "2":{\"mc_number\":\"Warehouse1\\\/2013-2014\\\/CO\\\/ABC Corp\\\/239\\\/101-Red-2\",\"config\":{\"S2\":10,\"S1\":10},\"delivered\":0},                  "3":{\"mc_number\":\"Warehouse1\\\/2013-2014\\\/CO\\\/ABC Corp\\\/239\\\/104-Black-3\",\"config\":{\"S1\":7,\"S2\":7,\"S5\":6},\"delivered\":0},               "4":{\"mc_number\":\"Warehouse1\\\/2013-2014\\\/CO\\\/ABC Corp\\\/239\\\/104-Black-4\",\"config\":{\"S1\":7,\"S2\":7,\"S5\":6},\"delivered\":0},              "5":{\"mc_number\":\"Warehouse1\\\/2013-2014\\\/CO\\\/ABC Corp\\\/239\\\/104-Black-5\",\"config\":{\"S1\":6,\"S2\":6,\"S5\":7},\"delivered\":0}
                               ]",
                         "delivery_note_id":"0",
                         "customer_order_id":"314"
                 }
}

mc内部的json数组如下所示 –

[
   "1":{
      "mc_number":"Warehouse1\/2013-2014\/CO\/ABC Corp\/239\/101-Red-1",
      "config":{
         "S2":10,
         "S1":10
      },
      "delivered":0
   },
   "2":{
      "mc_number":"Warehouse1\/2013-2014\/CO\/ABC Corp\/239\/101-Red-2",
      "config":{
         "S2":10,
         "S1":10
      },
      "delivered":0
   },
   "3":{
      "mc_number":"Warehouse1\/2013-2014\/CO\/ABC Corp\/239\/104-Black-5",
      "config":{
         "S1":6,
         "S2":6,
         "S5":7
      },
      "delivered":0
   }
]

我试图使用jquery解析其中的每个对象,每个对象如下 –

{
   "mc_number":"Warehouse1\/2013-2014\/CO\/ABC Corp\/239\/101-Red-1",
   "config":{
      "S2":10,
      "S1":10
   },
   "delivered":0
}

为了获得上述对象,我使用以下jquery代码 –

$.each(json_mc,function(){
       // What should the code be so as to get each individual objects.         
});

这是每次都应该让我 –

{
      "mc_number":"Warehouse1\/2013-2014\/CO\/ABC Corp\/239\/101-Red-1",
      "config":{
         "S2":10,
         "S1":10
      },
      "delivered":0
   }
您所追求的只是在每次迭代时设置的:

$.each(json_mc,function(){
    console.log(this);
});

更新

鉴于您显示的原始响应,您可能需要再次解码它:

$.each($.parseJSON(json_mc), function() {
    console.log(this);
});
网友评论