首页 > 解决方案 > Elixir,迭代嵌套地图

问题描述

我是 elixir 的新手,我正在尝试从非常嵌套的地图中获取一些文本。

因此,我正在对此链接发出获取请求,并使用 Jason.decode 对其进行解码。

我想要做的是迭代它并获取每个文本值(sections->0->content->0->text)。

最后,我只希望它是所有文本值的大字符串

(链接可以随时更改,因此可能会有更多地图等)

提前致谢!

标签: loopsdictionaryelixirwikia

解决方案


您可以使用Enum管道运算符|>来枚举数据结构并提取所需的部分。

例如:

def pokedex(id) do
  HTTPoison.get!("https://pokemon.fandom.com/api/v1/Articles/AsSimpleJson?id=#{id}")
  |> Map.get(:body)
  |> Jason.decode!()
  |> Map.get("sections")
  |> Enum.reject(fn %{"content" => content} -> content === [] end)
  |> Enum.flat_map(fn %{"content" => content} ->
    content
    |> Enum.filter(fn %{"type" => type} -> type in ["text", "paragraph"] end)
    |> Enum.map(fn %{"text" => text} -> text end)
  end)
  |> Enum.join("\n")
end

细分:

  • Map.get("sections")选择sections.
  • Enum.reject(...)忽略空白部分。
  • Enum.flat_map遍历各个部分,获取contents每个部分的,使用内部函数对其进行转换,然后将结果展平为单个列表。
    • Enum.filter(...)只处理type属性为textor的内容paragraph
    • Enum.maptext从每个内容映射中提取属性。
  • Enum.join用换行符连接生成的字符串列表。

推荐阅读