json - 从 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", ....]
解决方案
你正在寻找Enum.map/2
. 此方法在给定列表/可枚举中的每个项目上调用传递的函数:
Enum.map(response, fn item -> item["email"] end )
或者,您可以使用简写并使其简洁:
Enum.map(response, &(&1["email"]))
外部资源:请参阅this和this以了解一般函数式编程中映射的概念。
旁注: flat_map/2
是一种变体map/2
,期望“映射结果”是另一个列表(因此它可以与其余映射结果连接和展平)。
推荐阅读
- php - php : 为什么这种不正确的数据库请求方式不易受到攻击
- python - HttpsCallable 从 python 返回
- python - 如何分配用户在井字游戏中输入的值?
- java - 我需要检查每个已安装的应用程序并检查是否允许使用移动数据连接
- python - 解析 Redis MONITOR 消息
- microsoft-graph-api - Graph Explorer ErrorInvalidIdMalformed
- python - 在 Django 的外键中,即时类型更改为 int
- html - 如何根据宽度百分比设置高度 - 纯 CSS
- azure - 创建新的 API 管理服务实例后,为什么内置管理员帐户无法登录开发者门户批准注册的应用程序?
- node.js - 如何查询 mongodb 以比较对象数组?