1

我正在使用以下网址请求方向:

http://maps.googleapis.com/maps/api/directions/json?origin=43.656877,-79.32085&destination=Montreal&sensor=false

然后,谷歌发回一个巨大的 JSON,我想以比这更好的方式访问这些步骤:

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"]

有没有更漂亮的方式来访问 end_location 而不必使用所有这些数组表示法?我曾想过使用 OpenStruct,但也不理想。

4

1 回答 1

3

您可以替换[0]first,这是更多字符,但概念更简单,速度稍快。

response["routes"].first["legs"].first["steps"].first["end_location"]

或者,您也可以这样做:

["routes", 0, "legs", 0, "steps", 0, "end_location"].inject(response, &:fetch)
于 2012-10-30T16:47:12.660 回答