Reputation: 1701
I'm requesting directions with the following url:
http://maps.googleapis.com/maps/api/directions/json?origin=43.656877,-79.32085&destination=Montreal&sensor=false
Then, Google sends back a huge JSON and I want to access the steps in a nicer way than this:
response = open("http://maps.googleapis.com/maps/api/directions/json?origin=#{lat1},#{lng1}&destination=#{lat2},#{lng2}&sensor=false").read
response = JSON.parse(response)
response["routes"][0]["legs"][0]["steps"][0]["end_location"]
Is there a more beautiful way to access the end_location without having to use all these array notation? I thought of using OpenStruct, but it would not be ideal either.
Upvotes: 1
Views: 1206
Reputation: 168071
You can replace [0]
with first
, which is more characters but simpler concept and slightly faster.
response["routes"].first["legs"].first["steps"].first["end_location"]
Or, you can also do this:
["routes", 0, "legs", 0, "steps", 0, "end_location"].inject(response, &:fetch)
Upvotes: 3