Get data of a deep list

So im trying to get data of a list within a list within a list

  "items" => [
      "attackLog" => [],
      "capitalTotalLoot" => 0,
      "defenseLog" => [
          "attackCount" => 6,
          "attacker" => %{
            "badgeUrls" => %{
              "large" => "",
              "medium" => "",
              "small" => ""

So basically, the first list where all the data is in, is called items, then within that, there is another list called defenseLog, and in there, there is another called attacker- and I want all of that data from there.

I tried the following so far:

def main(tag) do
    data = fetch_data_from_api(tag)
    Kernel.get_in(data, ["items", "defenseLog", "attacker"])

but this errors:

* (ArgumentError) the Access calls for keywords expect the key to be an atom, got: "defenseLog"
1 Like

get_in/2 allows you to access elements of a nested structure by naming their keys, but if at some point in the hierarchy you need to grab all elements of a list, Access.all/0 is your friend (I just found out about it to be honest :smile: )

Something like this might work:

|> get_in(["items", Access.all(), "defenseLog",  Access.all(), "attacker"]) 
|> List.flatten()

Also check out Pathex.


this returns

** (FunctionClauseError) no function clause matching in :lists.flatten/1    
    The following arguments were given to :lists.flatten/1:
        # 1
    (stdlib 4.1) lists.erl:648: :lists.flatten/1
    iex:3: (file)

You did not deal with nil returned by get_in if the search fail… and nil is not an acceptable value for :lists.flatten

You should wrap get_in in a case statement, and treat each case.

yea I tried all kind of case statement but at the end of the day I even got larger error :confused: could you give me a hand maybe?