1

I have the following JSON-encoded data being returned and need to process it with jQuery.
How can I access different depots and vehicle data inside this list using jQuery.getJSON()'s callback function?

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

The JSON-encoded data:

// 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 Answer 1

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"
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.