Elixir:从嵌套列表中提取元素

时间:2016-11-04 12:26:51

标签: elixir

我有以下带有一些混合数据的JSON文件。

例如,我想从social_link link中提取Facebook。

[
  [
    "social_links",
    [
      {
        "image":"http://example.com/icons/facebook.svg",
        "link":"https://www.facebook.com/Example",
        "alt":"Facebook"
      },
      {
        "image":"http://example.com/icons/twitter.svg",
        "link":"https://twitter.com/example",
        "alt":"Twitter"
      },
      {
        "image":"http://example.com/icons/linkedin.svg",
        "link":"https://www.linkedin.com/company/example",
        "alt":"Linkedin"
      },
      {
        "image":"http://example.com/icons/icons/rounded_googleplus.svg",
        "link":"https://plus.google.com/+example",
        "alt":"Google Plus"
      }
    ]
  ]
]

在Ruby中,我们可以使用以下代码从嵌套数据结构中获取数据:

hsh = JSON.parse str
hsh.select{ |k, _| k == "social_links" }[0][1].find { |k, _| k["alt"] == "Facebook"}["link"]
=> "https://www.facebook.com/Example"

如何在Elixir中做同样的事情?从嵌套结构中提取数据的最佳实践是什么?

1 个答案:

答案 0 :(得分:2)

我是这样做的,使用Poison进行解析:

[_, links] = Poison.decode!(json) |> Enum.find(&match?(["social_links" | _], &1))
link = Enum.find_value(links, fn %{"alt" => "Facebook", "link" => link} -> link end)

完整代码:

json = """
[
  [
    "social_links",
    [
      {
        "image":"http://example.com/icons/facebook.svg",
        "link":"https://www.facebook.com/Example",
        "alt":"Facebook"
      },
      {
        "image":"http://example.com/icons/twitter.svg",
        "link":"https://twitter.com/example",
        "alt":"Twitter"
      },
      {
        "image":"http://example.com/icons/linkedin.svg",
        "link":"https://www.linkedin.com/company/example",
        "alt":"Linkedin"
      },
      {
        "image":"http://example.com/icons/icons/rounded_googleplus.svg",
        "link":"https://plus.google.com/+example",
        "alt":"Google Plus"
      }
    ]
  ]
]
"""

[_, links] = Poison.decode!(json) |> Enum.find(&match?(["social_links" | _], &1))
link = Enum.find_value(links, fn %{"alt" => "Facebook", "link" => link} -> link end)
IO.puts link

输出:

https://www.facebook.com/Example