Page 1 of 1

Extracting information from JSON

Posted: 22 Nov 2019 10:57
by benbrown
I want to extract the trip duration from a Google Maps navigation request. The response is simple and I only need 1 value from it: the duration text.

How do I get to rows > elements > duration > text > "33 mins" in this example?

Code: Select all

{  "destination_addresses" : [ "Holloway, London N7 6PG, UK" ],
   "origin_addresses" : [ "Westminster, London, UK" ],
   "rows" : [
      {  "elements" : [
            { "distance" : {
                  "text" : "9.0 km",
                  "value" : 8960
               },
               "duration" : {
                  "text" : "33 mins",
                  "value" : 1980
               },
               "status" : "OK"
} ] } ], "status" : "OK" }
The solution is probably similar to this earlier answer I found but I can't figure out how to drill down into the deeper levels of the response.

Re: Extracting information from JSON

Posted: 22 Nov 2019 16:48
by Micky Micky
If you have that data stored in a string called RESPONSE then:

js = fromJSON(response);

duration = js["rows"][0]["elements"][0]["duration"]["text"];

The key to JSON is 'parent and child'.

For example:

js = fromJSON(response);

destination = js["destination_addresses"];

There's nothing more in that to retrieve.


Hope this helps

Re: Extracting information from JSON

Posted: 22 Nov 2019 16:55
by benbrown
duration = js["rows"][0]["elements"][0]["duration"]["text"];
That's exactly right. Thank you very much!

I would never have figured that out - so many consecutive brackets!