2013-04-01 152 views
3

在下面的代碼:發送作爲響應jQuery的解析JSON對象和陣列

$.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 
    } 

回答

7

你後是什麼簡單地說是this,它是在每次迭代中設置的:

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

更新

鑑於還有你的原始響應,您可能需要將其解碼一次:

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

感謝您的回答插孔,但是當我用您的解決方案試過我越來越[, {,「,m,c ...........等等。所以,你可以提出一個建議,告訴我從{到}的整個對象的獲取方式。 –

+0

@ GaneshYoganand它工作正常[在這裏](http://jsbin.com/uwijan/1/)。你得到的結果可能是由於你沒有顯示的代碼。 –

+0

我得到這樣的日誌。 String {0 =「m」} add_sales_invoice(line 294)String {0 =「c」} add_sales_invoice(line 294)String {0 =「_」} add_sales_invoice(line 294)String {0 =「n」} –