如何在Elixir中使用嵌套数据结构

特里斯坦·奥尼尔

尽管我对Elixir语言有点陌生,但是我仍在尝试使用Elixir中的Google Maps地理编码API,因此使用嵌套数据结构使我难以理解。

我正在使用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的深层嵌套数据结构中提取值的最佳方法是什么?朝着正确方向提出的任何解决方案或推动都将不胜感激。

乔希·布莱克(Josh Black)

查看Seth Falcon的ej库的源代码:

https://github.com/seth/ej

使用递归,它或多或少地完成了您想要做的事情。

我不是Elixir专家,但是您也许可以直接使用该库。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章