javascriptjqueryjsonmapquest

Iterate through JSON from MapQuest API


I'm parsing JSON response from the MapQuest API. I need all of the 'narratives' from the 'legs' node under 'maneuvers' (legs-> maneuvers -> get all narratives), but I cannot figure it out.

I can get most of the values like so:

$(function(){
   var mq = jQuery.parseJSON(jsonResponse);
   $("#fuel").html(mq.renderMatrixResults[0].route.fuelUsed);
   $("#rtime").html(mq.renderMatrixResults[0].route.realTime);
});

Part of JSON response:

{
    "renderMatrixResults": [
        {
            "route": {
                "hasTollRoad": true,
                "computedWaypoints": [

                ],
                "fuelUsed": 2.24,
                "hasUnpaved": false,
                "hasHighway": true,
                "realTime": 5556,
                "boundingBox": {
                    "ul": {
                        "lng": -74.240074,
                        "lat": 40.662548
                    },
                    "lr": {
                        "lng": -74.132072,
                        "lat": 40.573451
                    }
                },
                "distance": 38.998,
                "time": 5523,
                "hasSeasonalClosure": false,
                "locations": [
                    {
                        "latLng": {
                            "lng": -74.18862,
                            "lat": 40.609712
                        },
                        "adminArea4": "Brooklyn",
                        "adminArea5Type": "City",
                        "adminArea4Type": "County",
                        "adminArea5": "Brooklyn",
                        "street": "1234 Test Lane",
                        "adminArea1": "US",
                        "adminArea3": "NY",
                        "type": "s",
                        "displayLatLng": {
                            "lng": -74.188621,
                            "lat": 40.60971
                        },
                        "linkId": 33589148,
                        "postalCode": "10001-6992",
                        "sideOfStreet": "L",
                        "dragPoint": false,
                        "adminArea1Type": "Country",
                        "geocodeQuality": "POINT",
                        "geocodeQualityCode": "P1AAA",
                        "adminArea3Type": "State"
                    },
                    {
                        "latLng": {
                            "lng": -74.194858,
                            "lat": 40.601623
                        },
                        "adminArea4": "Brooklyn",
                        "adminArea5Type": "City",
                        "adminArea4Type": "County",
                        "adminArea5": "Brooklyn",
                        "street": "5678 Example Street",
                        "adminArea1": "US",
                        "adminArea3": "NY",
                        "type": "s",
                        "displayLatLng": {
                            "lng": -74.194854,
                            "lat": 40.601623
                        },
                        "linkId": 33361764,
                        "postalCode": "10001-5483",
                        "sideOfStreet": "R",
                        "dragPoint": false,
                        "adminArea1Type": "Country",
                        "geocodeQuality": "POINT",
                        "geocodeQualityCode": "P1AAA",
                        "adminArea3Type": "State"
                    }
                ],
                "hasCountryCross": false,
                "legs": [
                    {
                        "hasTollRoad": false,
                        "index": 0,
                        "roadGradeStrategy": [
                            [

                            ]
                        ],
                        "hasHighway": false,
                        "hasUnpaved": false,
                        "distance": 0.882,
                        "time": 145,
                        "origIndex": 1,
                        "hasSeasonalClosure": false,
                        "origNarrative": "Go west on some road",
                        "hasCountryCross": false,
                        "formattedTime": "00:02:25",
                        "destNarrative": "Proceed to 789 GIRAFFE STREET",
                        "destIndex": 1,
                        "maneuvers": [
                            {
                                "signs": [

                                ],
                                "index": 0,
                                "maneuverNotes": [

                                ],
                                "direction": 4,
                                "narrative": "Start out going south on Elephant Avenue.",
                                "iconUrl": "https://content.mapquest.com/mqsite/turnsigns/icon-dirs-start_sm.gif",
                                "distance": 0.57,
                                "time": 79,
                                "linkIds": [

                                ],
                                "streets": [
                                    "Elephant Avenue"
                                ],
                                "attributes": 0,
                                "transportMode": "AUTO",
                                "formattedTime": "00:01:19",
                                "directionName": "South",
                                "mapUrl": "https://www.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luur20uanq,b0=o5-9ayxdw&type=map&size=225,160&pois=purple-1,40.60971,-74.188621,0,0|purple-2,40.602351999999996,-74.189582,0,0|�er=40.606031,-74.18910149999999&zoom=10&rand=-1416511403&session=53c1fb45-030d-0004-02b7-16b5-00163e4c0d3f",
                                "startPoint": {
                                    "lng": -74.188621,
                                    "lat": 40.60971
                                },
                                "turnType": 2
                            },
                            {
                                "signs": [

                                ],
                                "index": 1,
                                "maneuverNotes": [

                                ],
                                "direction": 7,
                                "narrative": "Turn right onto Tiger Blvd.",
                                "iconUrl": "https://content.mapquest.com/mqsite/turnsigns/rs_right_sm.gif",
                                "distance": 0.269,
                                "time": 56,
                                "linkIds": [

                                ],
                                "streets": [
                                    "Tiger Blvd"
                                ],
                                "attributes": 0,
                                "transportMode": "AUTO",
                                "formattedTime": "00:00:56",
                                "directionName": "West",
                                "mapUrl": "https://www.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luur20uanq,b0=o5-9ayxdw&type=map&size=225,160&pois=purple-2,40.602351999999996,-74.189582,0,0|purple-3,40.601127,-74.194366,0,0|�er=40.601739499999994,-74.191974&zoom=12&rand=-1416511403&session=53c1fb45-030d-0004-02b7-16b5-00163e4c0d3f",
                                "startPoint": {
                                    "lng": -74.189582,
                                    "lat": 40.602352
                                },
                                "turnType": 2
                            }

Solution

  • Haven't tested it but here is the idea. You can use a function that will traverse object tree and collect items specified by a path.

    function getPath(path, obj) {
         var name, value;
         path = path instanceof Array ? path: path.split('.'); //convert path to array
         name = path.shift(); //get the first name
         value = obj[name]; //extract value
         if(!path.length || value == null) { //last name or value is null or undefined
             return value;
         }
         if(value instanceof Array) { //if value is array - concat
             return [].concat.apply([], value.map(function(item){ 
                                     return getPath(path.slice(0), item);
                                  }));
         } 
         return getPath(path, value); //else go deeper
    }
    

    Usage:

    var narratives 
         = getPath('renderMatrixResults.route.legs.maneuvers.narrative', mq);
    

    I believe the path is correct.