2016-11-04 47 views
0

我有以下帶有一些混合數據的JSON文件。Elixir:從嵌套列表中提取元素

例如,我想從Facebook提取social_linklink

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

如何做藥劑同樣的事情?從嵌套結構中提取數據的最佳實踐是什麼?

回答

2

我會做這樣的使用毒藥解析:

[_, 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