October 22, 2024
Chicago 12, Melborne City, USA
jQuery

Extracting info from JSON response


I’m trying to get the last value of "TMiles" in the following JSON.

[{
  "__type": "MileageReport:http:\/\/pcmiler.alk.com\/APIs\/v1.0",
  "RouteID": null,
  "ReportLines": [{
    "Stop": {
      "Address": {
        "StreetAddress": "Apple Park Way",
        "City": "Cupertino",
        "State": "CA",
        "Zip": "95014",
        "County": "Santa Clara",
        "Country": "United States",
        "SPLC": null,
        "CountryPostalFilter": 0,
        "AbbreviationFormat": 0,
        "StateName": "California",
        "StateAbbreviation": "CA",
        "CountryAbbreviation": "US"
      },
      "Coords": {
        "Lat": "37.334866",
        "Lon": "-122.014282"
      },
      "Region": 4,
      "Label": "",
      "PlaceName": "",
      "TimeZone": "PDT",
      "Errors": [],
      "SpeedLimitInfo": null,
      "ConfidenceLevel": "Exact",
      "DistanceFromRoad": 0,
      "CrossStreet": null,
      "TimeZoneOffset": "GMT-7:00",
      "TimeZoneAbbreviation": "PDT",
      "IsDST": true
    },
    "LMiles": "0.000",
    "TMiles": "0.000",
    "LCostMile": "0.00",
    "TCostMile": "0.00",
    "LHours": "0:00",
    "THours": "0:00",
    "LTolls": "0.00",
    "TTolls": "0.00",
    "LEstghg": "0.0",
    "TEstghg": "0.0",
    "EtaEtd": null
  }, {
    "Stop": {
      "Address": {
        "StreetAddress": "22-26 West 34th Street",
        "City": "New York",
        "State": "NY",
        "Zip": "10001",
        "County": "New York",
        "Country": "United States",
        "SPLC": null,
        "CountryPostalFilter": 0,
        "AbbreviationFormat": 0,
        "StateName": "New York",
        "StateAbbreviation": "NY",
        "CountryAbbreviation": "US"
      },
      "Coords": {
        "Lat": "40.748462",
        "Lon": "-73.984770"
      },
      "Region": 4,
      "Label": "",
      "PlaceName": "",
      "TimeZone": "EDT",
      "Errors": [],
      "SpeedLimitInfo": null,
      "ConfidenceLevel": "Exact",
      "DistanceFromRoad": 0.003,
      "CrossStreet": null,
      "TimeZoneOffset": "GMT-4:00",
      "TimeZoneAbbreviation": "EDT",
      "IsDST": true
    },
    "LMiles": "2945.142",
    "TMiles": "2945.142",
    "LCostMile": "5690.99",
    "TCostMile": "5690.99",
    "LHours": "55:44",
    "THours": "55:44",
    "LTolls": "284.55",
    "TTolls": "284.55",
    "LEstghg": "9788.0",
    "TEstghg": "9788.0",
    "EtaEtd": null
  }],
  "TrafficDataUsed": false
}]

I’ve tried using multiple methods but to no avail. Here’s one i tried:

dataM = 'supplied json
var lastTMiles = dataM[0].ReportLines[dataM[0].ReportLines.length - 1].TMiles;

Here is my error:

Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    at reqhttpM.onreadystatechange (mileage-finder.asp:280:60)

I’m not quite sure what to do here. I’ve edited this to add the ajax call and I’m hoping this will give more insight as to what’s going on.

function dictToParamString(obj) {
  var str = [];
  for (var p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
  return str.join("&");
}


    reqhttpM = new XMLHttpRequest();
    var url = "https://pcmiler.alk.com/apis/rest/v1.0/Service.svc/route/routeReports?";


    //Lon first, then lat
    var params = {
      stops: sLon+','+sLat+';'+eLon+','+eLat,
      reports: "Mileage"
    };

    var urlQuery = url + dictToParamString(params);
    reqhttpM.open("GET", urlQuery, true);
    reqhttpM.setRequestHeader("Content-type", "application/json");
    reqhttpM.setRequestHeader("Authorization", "Z3AFB2A60E01D01840BB58D19928814B2D");
    reqhttpM.responseType = "arraybuffer";

    reqhttpM.onreadystatechange = function () {
      // Call a function when the state changes.
      if (reqhttpM.readyState == 4 && reqhttpM.status == 200) {
        var res = reqhttpM.response;
        if (res) {
          var uInt8Array = new Uint8Array(res);
          var i = uInt8Array.length;
          var binaryString = new Array(i);
          while (i--) {
            binaryString[i] = String.fromCharCode(uInt8Array[i]);
          }
          dataM = binaryString.join('');
          
        console.log(dataM);
          
        //lastTMiles = dataM[0].ReportLines[dataM[0].ReportLines.length - 1].TMiles;
        
        const [firstEntry] = dataM;
        const { TMiles } = firstEntry.ReportLines.at(-1);
        
        //const lastReportLine = dataM[0].ReportLines.pop();
        //const lastTMiles = lastReportLine.TMiles;

        console.log(lastTMiles)
          
          //$('.miles').html(lastTMiles);
          
        }
      }
    };

reqhttpM.send()

Looking forward to responses. Thank you



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video