2013-08-02 54 views
3

我試圖在Elixir中使用Google Maps地理編碼API,儘管我對該語言有點新,所以使用嵌套數據結構工作正在避開我。如何在Elixir中使用嵌套數據結構

我使用HTTPotion從地理編碼端點獲取JSON,並使用JSEX將其解析爲Elixir數據結構(一系列嵌套列表和元組)。

defmodule Geocode do 
    def fetch do 
    HTTPotion.start 
    result = HTTPotion.get "http://maps.googleapis.com/maps/api/geocode/json?address=Fairfax,%20Vermont&sensor=false" 
    json = JSEX.decode result.body 
    end 
end 

下面現在分配給json。

{:ok, [{"results", [[{"address_components", [[{"long_name", "Fairfax"}, {"short_name", "Fairfax"}, {"types", ["locality", "political"]}], [{"long_name", "Franklin"}, {"short_name", "Franklin"}, {"types", ["administrative_area_level_2", "political"]}], [{"long_name", "Vermont"}, {"short_name", "VT"}, {"types", ["administrative_area_level_1", "political"]}], [{"long_name", "United States"}, {"short_name", "US"}, {"types", ["country", "political"]}]]}, {"formatted_address", "Fairfax, VT, USA"}, {"geometry", [{"bounds", [{"northeast", [{"lat", 44.772892}, {"lng", -72.92268890000001}]}, {"southwest", [{"lat", 44.6330508}, {"lng", -73.08477409999999}]}]}, {"location", [{"lat", 44.6654963}, {"lng", -73.01032}]}, {"location_type", "APPROXIMATE"}, {"viewport", [{"northeast", [{"lat", 44.772892}, {"lng", -72.92268890000001}]}, {"southwest", [{"lat", 44.6330508}, {"lng", -73.08477409999999}]}]}]}, {"types", ["locality", "political"]}]]}, {"status", "OK"}]} 

我想從這個嵌套的數據結構中提取緯度和經度。我試過使用模式匹配,但由於結構相當複雜,相應的模式有點噩夢。雖然下面的工作,它不可能是一個很好的解決方案。

{_, [{_, [[_, _, { _, [{_, [{_, [{_, lat}, {_, lgn}]}, _]}, _, _, _] }, _]]}, _]} = json 

所以我的問題是從Elixir深層嵌套數據結構中提取值的最佳方法是什麼?任何解決方案或在正確的方向推動將不勝感激。

回答

8

退房源塞特獵鷹的EJ庫:

https://github.com/seth/ej

它或多或少你想要做什麼,使用遞歸。

我不是藥劑師專家,但您可能可以直接使用該藥劑庫。

+2

你應該可以使用ej和Elixir一樣好。像ej這樣的工具是現在的方法,但我們意識到,訪問和更新嵌套數據結構並不像預期的那麼容易,而且我們正在制定解決這些問題的提議。 –

4

的EJ庫看起來像一個不錯的選擇,但除了我會切到數據結構的心臟馬上:

{:ok, [{"results", results}, {"status", status}]} = JSEX.decode result.body 

,或者如果你總是隻使用第一個結果:

{:ok, [{"results", [geo_json | _]}, {"status", status}]} = JSEX.decode result.body 

然後我會使用geo_json數據結構上的ej庫。