首页 > 解决方案 > 从 JSON 数组中获取数据

问题描述

我有一个 JSON 数组:

response = [
  %{
    "created_at" => 1542757526,
    "email" => "bcs@yahoo.com",
    "first_name" => "rana",
    "id" => "YW1pcnBheWFyeUB5YWhvby5jb20=",
    "last_clicked" => nil,
    "last_emailed" => nil,
    "last_name" => "amir",
    "last_opened" => nil,
    "updated_at" => 1542759123
  },
  %{
    "created_at" => 1542757457,
    "email" => "abc@gmail.com",
    "first_name" => "rana",
    "id" => "cmFtaXIyNDI2QGdtYWlsLmNvbQ==",
    "last_clicked" => nil,
    "last_emailed" => nil,
    "last_name" => "amir",
    "last_opened" => nil,
    "updated_at" => 1542759001
  },
  # .......
]

我正在尝试获取变量email中所有项目的字段。response例子:

["bcs@yahoo.com", "xyz@gmail.com", ....]

标签: jsonelixirelixir-poison

解决方案


你正在寻找Enum.map/2. 此方法在给定列表/可枚举中的每个项目上调用传递的函数:

Enum.map(response, fn item -> item["email"] end )

或者,您可以使用简写并使其简洁:

Enum.map(response, &(&1["email"]))

外部资源:请参阅thisthis以了解一般函数式编程中映射的概念。

旁注: flat_map/2是一种变体map/2,期望“映射结果”是另一个列表(因此它可以与其余映射结果连接和展平)。


推荐阅读