Get data from a JSON Array

630 views Asked by At

I have a JSON array:

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

I'm trying to get the email field of all items in the response variable. Example:

["[email protected]", "[email protected]", ....]
2

There are 2 answers

1
Sheharyar On

You're looking for Enum.map/2. This method calls the passed function on every item in the given list/enumerable:

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

Alternatively, you can use the shorthand and make it concise:

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

External Resources: See this and also this to understand the concept of mapping in functional programming in general.

Side note: flat_map/2 is a variation of map/2 that expects the "mapped result" to be another list (so it can be joined and flattened with the rest of the mapped results).

0
Brett Beatty On

In addition to map, you could also look at comprehensions. Essentially they combine the functionality of Enum.map/2 & Enum.filter/2.

They allow you to do something like this:

for %{"email" => email} <- response, do: email

or this:

for item <- response, do: item["email"]

Note there's a subtle difference in behavior between the result of the two: the former will filter out any items that do not match the left-hand side (it will only keep maps with an "email" key), but the latter will map the items lacking an email to nil.