2011-10-01 132 views
1

我有以下JSON編碼數據被返回並需要使用jQuery處理它。
如何使用jQuery.getJSON()的回調函數訪問此列表中的不同倉庫和車輛數據?使用jQuery處理JSON

$.getJSON('url', function(data) { 
    // ...? 
}); 

的JSON編碼的數據:

// top-level result is a list of dictionaries 
[ 
    // return dictionary for each depot 

    { 
    depot: { 
     _id: 'D3', 
     intersection: { 
     first: 'Bay', 
     second: 'King' 
     }, 
     address: { 
     number: '100', 
     street: 'King street West', 
     city: 'Toronto', 
     province: 'ON', 
     postal_code: 'M5X 1B8' 
     }, 
    }, 
    // return dictionary for each car in that depot 
    vehicle: [{ 
     _id: 'V4', 
     _depot_id: 'D3', 
     model: 'Ford F150', 
     price: '80', 
     km_per_litre: '15', 
     cargo_cu_m: 'YES', 
     category: 'Truck', 
     image: 'www.coolcarz.com' 
     }, { 
     _id: 'V24', 
     _depot_id: 'D3', 
     model: 'Toyota Camry Hybrid', 
     price: '90', 
     km_per_litre: '25', 
     cargo_cu_m: 'YES', 
     category: 'Hybrid car', 
     image: 'www.coolcarz.com' 
     } 
    ] 
    }, 


    { 
    depot: { 
     _id: 'D9', 
     intersection: { 
     first: 'Bay', 
     second: 'Front' 
     }, 
     address: { 
     number: '161', 
     street: 'Bay', 
     city: 'Toronto', 
     province: 'ON', 
     postal_code: 'M5J 2S1' 
     }, 
    }, 
    // return dictionary for each car in that depot 
    vehicle: [{ 
     _id: 'V11', 
     _depot_id: 'D9', 
     model: 'Ford Crown Victoria', 
     price: '45', 
     km_per_litre: '13', 
     cargo_cu_m: 'YES', 
     category: 'Standard car', 
     image: 'www.coolcarz.com' 
     }, 
    ] 
    }, 

] 

回答

2
$.getJSON('url', function(data) { 
    alert(data.length);      // 2 
    alert(data[0].depot.intersection.second); // "King" 
    alert(data[0].vehicle[1].category);  // "Hybrid car" 
    alert(data[1].depot.address.city);   // "Toronto" 
});