So I’m trying to pull data from a JSON string (as seen below). When I decode the JSON using the code below, and then attempt to index the duration text, I get a nil return. I have tried everything and nothing seems to work.
Here is the Google Distance Matrix API JSON:
{ "destination\_addresses" : ["San Francisco, CA, USA"], "origin\_addresses" : ["Seattle, WA, USA"], "rows" : [{ "elements" : [ { "distance" : { "text" : "1,299 km", "value" : 1299026 }, "duration" : { "text" : "12 hours 18 mins", "value" : 44303 }, "status" : "OK" }] } ], "status" : "OK" }
And here is my code:
local json = require ("json") local http = require("socket.http") local myNewData1 = {} local SaveData1 = function (event) distanceReturn = "" distance = "" local URL1 = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Seattle&destinations=San+Francisco&mode=driving&&sensor=false" local response1 = http.request(URL1) local data2 = json.decode(response1) if response1 == nil then native.showAlert( "Data is nill", { "OK"}) print("Error1") distanceReturn = "Error1" elseif data2 == nill then distanceReturn = "Error2" native.showAlert( "Data is nill", { "OK"}) print("Error2") else for i = 1, #data2 do print("Working") print(data2[i].rows) for j = 1, #data2[i].rows, 1 do print("\t" .. data2[i].rows[j]) for k = 1, #data2[i].rows[k].elements, 1 do print("\t" .. data2[i].rows[j].elements[k]) for g = 1, #data2[i].rows[k].elements[k].duration, 1 do print("\t" .. data2[i].rows[k].elements[k].duration[g]) for f = 1, #data2[i].rows[k].elements[k].duration[g].text, 1 do print("\t" .. data2[i].rows[k].elements[k].duration[g].text) distance = data2[i].rows[k].elements[k].duration[g].text distanceReturn = data2[i].rows[k].elements[k].duration[g].text end end end end end end timer.performWithDelay (100, SaveData1, 999999)