Handling result in JSON

Could help me with this json?

json = 
[
%{
roles: "none",
assignments: [
      %{ 
        assignee: %{
          html_url: "https://test.com",
          id: "111111",
          summary: "Crypto ADA",
        },
        at: "2021-04-22T22:00:42-03:00"
      },
      %{ 
        assignee: %{
          html_url: "https://test.com",
          id: "222222",
          summary: "Crypto WIN",
        },
        at: "2021-04-22T22:00:42-03:00"
      },
      %{ 
        assignee: %{
          html_url: "https://test.com",
          id: "333333",
          summary: "Crypto Elongate",
        },
        at: "2021-04-22T22:00:42-03:00"
      },
      %{ 
        assignee: %{
          html_url: "https://test.com",
          id: "44444",
          summary: "Crypto Safemoon",
        },
        at: "2021-04-22T22:00:42-03:00"
      },
      %{ 
        assignee: %{
          html_url: "https://test.com",
          id: "55555",
          summary: "Crypto BTT",
        },
        at: "2021-04-22T22:00:42-03:00"
      }
    ]
}
]

I’m using Enum.map, to do the deal.
Thus

Enum.map(json, &%{assignments: &1[:assignments]})

Currently I need the variable “assignments” to show all the names in a string.
Staying that way

&1[:assignments] = “Crypto ADA, Crypto WIN, Crypto Elongate, Crypto Safemoon, Crypto BTT”

My current difficulty and taking the summary field

How should I do this within Enum?

You could just enumerate on the json[:assignments] and do &1.assignee.summary

Whenever I try to enter “assignee” it returns an error.

I have tried several ways.

Enum.map(incidents, &%{assignments: &1[:assignments][:assignee]})
2.
Enum.map(incidents, &%{assignments: &1.assignments.assignee})
3.
Enum.map(incidents, &%{assignments: &1.assignments[:assignee]})

Error displayed

** (ArgumentError) you attempted to apply :assignee on [%{assignee: %{html_url: “https:// …
}], :assignee, [])
(stdlib 3.14) erl_eval.erl:680: :erl_eval.do_apply/6
(stdlib 3.14) erl_eval.erl:786: :erl_eval.eval_map_fields/5
(stdlib 3.14) erl_eval.erl:263: :erl_eval.expr/5
(elixir 1.11.2) lib/enum.ex:1399: Enum.”-map/2-lists^map/1-0-"/2
)

the code you sent previously is different than the second one. if your json is incidents then it would be

Enum.map(incidents.assignments, & &1.assignee.summary)

I would use something like this (assuming the exact json structure in the top post)

iex(66)> json |> get_in([Access.at(0), :assignments, Access.all(), :assignee, :summary]) |> Enum.join(", ")
"Crypto ADA, Crypto WIN, Crypto Elongate, Crypto Safemoon, Crypto BTT"

3 Likes

When writing code like this, you want to carefully consider what shape the data is in at each step:

  • start with Enum.map(incidents, ...). So inside the ..., &1 will be a single incident - a map
  • &1.assignments or &1[:assignments]: either of these returns a LIST of assignments
  • so both &1.assignments.assignee and &1[:assignments].assignee complain, because a list is not a map