Elixir:从嵌套列表中提取元素
我有以下JSON文件,其中包含一些混合数据 例如,我想从Facebook的Elixir:从嵌套列表中提取元素,elixir,Elixir,我有以下JSON文件,其中包含一些混合数据 例如,我想从Facebook的社交链接链接中提取 [ [ "social_links", [ { "image":"http://example.com/icons/facebook.svg", "link":"https://www.facebook.com/Example", "alt":"Facebook" }, { "imag
社交链接
链接
中提取
[
[
"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"
如何在长生不老药中做同样的事情?从嵌套结构中提取数据的最佳做法是什么?我将使用毒药进行解析:
[_, 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
我会像这样使用毒药进行解析:
[_, 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