-4

im using backbone, jquery, underscore and i'd like to get at some JSON ive got in a local file.

Im currently using

        //Will get data but no access to individual objects
        $.getJSON('carinfo.json', function(data){
            console.log(data);
            var data2 = data['unitId'];
            console.log(data2);


        });

to pull the JSON into the data variable but i dont know where to go from here. How would i for instance get back all of the values from the field name 'carID'?

This is what one of my JSON entries looks like

{
    "carID": "xx",
    "xxx": {
        "unitID": "xxxxxxx",
        "positionHistory": [{
            "lat": "xxxxx",
            "long": "xxxxxxxx",
            "time": "xxxxxxxxxx",
            "status": "1",
            "estimatedSpeed": "0",
            "lastSoundFileName": "xxxxx",
            "lastSoundRange": "12",
            "lastSoundTime": "xxxxxxxx",
            "isToday": false,
            "minutesAgo": xxxxxx
        }]
    },
    "registration": "xxxxxxx",
    "color": "xxxxxxxx",
    "phone": "",
    "model": "xxxx"
}

Edit: using data.carID returns undefined.

Screenshot of chrome console output

enter image description here

lorless
  • 4,126
  • 8
  • 30
  • 41

2 Answers2

1

Updated to account for the fact that your data is an array.

$.getJSON('carinfo.json', function (data) {
    // Loop over all the cars in data
    for (var i = 0; i < data.length; i++) {
        var car = data[i];
        car.carID === 'xx';  // just do data.whatever to get the value
        car.phone === '';

        car.xxx.positionHistory[0].status === '1'; // data.xxx.positionHistory is an array;
                                            // use [i] to get the ith element

        car.xxx['unitID'] === 'xxxxxxx';     // You can use bracket notation with a
                                      // string to get an object property if
                                      // you prefer

    }
});
Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
0

If your JSON is an array of car entries, then you need to access them as such:

$.getJSON('carinfo.json', function (data) {
    for(var i=0; i<data.length; i++) {
        console.log(data[i].carID);
    }

    // or access without a loop:
    console.log(data[0].carID);
    console.log(data[1].carID);
    console.log(data[0].xxx.unitID);
}); 
MrCode
  • 63,975
  • 10
  • 90
  • 112