I am working with a location API and need to retrieve the adminArea1
value in order to save the country information into a JavaScript variable. How can I access this specific value from the provided JSON data? I already have experience importing JSON as an object in JavaScript, so that part is not an issue. The object containing the data is named locationResults
.
{
"results": [{
"locations": [{
"latLng": {
"lng": -76.329999,
"lat": 40.0755
},
"adminArea4": "Lancaster County",
"adminArea5Type": "City",
"adminArea4Type": "County",
"adminArea5": "Lancaster",
"street": "Granite Run Drive",
"adminArea1": "US", //THE VALUE I WANT
"adminArea3": "PA",
"type": "s",
"displayLatLng": {
"lng": -76.333129,
"lat": 40.07657
},
"linkId": 0,
"postalCode": "17601",
"sideOfStreet": "N",
"dragPoint": false,
"adminArea1Type": "Country",
"geocodeQuality": "ADDRESS",
"geocodeQualityCode": "L1AAA",
"mapUrl": "http://open.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luur2du2n1,bn=o5-9ar2l0&type=map&size=225,160&pois=purple-1,40.0755,-76.329999,0,0|¢er=40.0755,-76.329999&zoom=15&rand=-320722776",
"adminArea3Type": "State"
}],
"providedLocation": {
"latLng": {
"lng": -76.329999,
"lat": 40.0755
}
}
}],
"options": {
"ignoreLatLngInput": false,
"maxResults": -1,
"thumbMaps": true
},
"info": {
"copyright": {
"text": "© 2014 MapQuest, Inc.",
"imageUrl": "http://api.mqcdn.com/res/mqlogo.gif",
"imageAltText": "© 2014 MapQuest, Inc."
},
"statuscode": 0,
"messages": []
}
}
When using the following code:
$.getJSON(reverseGeoRequestURL, function(reverseGeoResult){
window.country = reverseGeoResult.results[0].adminArea1;
console.log(window.country);
});
The console outputs "undefined".
Solution
The structure of this JSON data is complex. To access the desired value, use the following path:
locationResults.results[0].locations[0].adminArea1;