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. Looking forward to responses. Thank you
2
Answers
A good way for you to do that is creating two variables, like this:
Note that the first variable uses the
.pop()
, this function always gets the last item from the array. And the second variable accesses theTMiles
field from the last report line.Modern runtimes allow the use of
at()