使用jQuery处理JSON

时间:2011-10-01 21:10:32

标签: json jquery

我返回了以下JSON编码数据,需要使用jQuery进行处理 如何使用jQuery.getJSON()的回调函数访问此列表中的不同软件仓库和车辆数据?

$.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'
      },
    ]
  },

]

1 个答案:

答案 0 :(得分: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"
});