2016-11-04 8 views
0

Ich habe die folgende JSON-Datei mit einigen gemischten Daten.Elixir: Element aus verschachtelten Listen extrahieren

Zum Beispiel möchte ich aus social_linklink für Facebook extrahieren.

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

In Ruby können wir Daten aus verschachtelten Datenstrukturen folgenden Code erhalten:

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

Wie das Gleiche in Elixir zu tun? Was ist die beste Vorgehensweise, um Daten aus verschachtelten Strukturen zu extrahieren?

Antwort

2

Ich würde es tun, wie diese mit Gift für die Analyse:

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

Voll Code:

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 

Ausgang:

https://www.facebook.com/Example 
Verwandte Themen