t.t

t.t

Trying to access a key inside a map

i want to access the “defaultValue” key.

%{
  "category" => {:ok,
   %{
     "defaultValue" => 10,
     "detailed" => [
       %{"categoryName" => "test", "categoryValue" => 23}
     ],
     "total" => 1
   }}
}
iex(56)> test_map["category"]
{:ok,
 %{
   "defaultValue" => 10,
   "detailed" => [%{"categoryName" => "test", "categoryValue" => 23}],
   "total" => 1
 }}

normally, i’d do this: test_map["category"]["defaultValue"]

but i get this error in return:

iex(57)> test_map["category"]["defaultValue"]
** (FunctionClauseError) no function clause matching in Access.get/3    
    
    The following arguments were given to Access.get/3:
    
        # 1
        {:ok,
         %{
           "defaultValue" => 10,
           "detailed" => [%{"categoryName" => "test", "categoryValue" => 23}],
           "total" => 1
         }}
    
        # 2
        "defaultValue"
    
        # 3
        nil
    
    Attempted function clauses (showing 5 out of 5):
    
        def get(%module{} = container, key, default)
        def get(map, key, default) when is_map(map)
        def get(list, key, default) when is_list(list) and is_atom(key)
        def get(list, key, _default) when is_list(list)
        def get(nil, _key, default)
    
    (elixir) lib/access.ex:265: Access.get/3

i noticed i have a tuple with a atom :ok and a map inside it, and that’s probably why i can’t access my “defaultValue” key but i’m new in elixir/functional programming and i am having a hard time trying to find the solution.

Marked As Solved

kokolegorille

kokolegorille

Yes You can…

I would say FP is made of pipeline of transformation.

Enum.reduce test_map, %{}, fn {k, {:ok, v}}, acc -> Map.put(acc, k, v) end

Also Liked

kokolegorille

kokolegorille

Hello and welcome,

iex(1)> elem(test_map["category"], 1)["defaultValue"]
10

BTW it is kind of ugly to have this ok tuple inside, and I would think of reshaping the data first.

emoragaf

emoragaf

I totally missed the tuple, but you can use the get_in ability to pass functions to handle the tuples

map = %{
  "category" => {:ok,
   %{
     "defaultValue" => 10,
     "detailed" => [
       %{"categoryName" => "test", "categoryValue" => 23}
     ],
     "total" => 1
   }}
}
cleaned_map = %{
  "category" =>%{
     "defaultValue" => 10,
     "detailed" => [
       %{"categoryName" => "test", "categoryValue" => 23}
     ],
     "total" => 1
   }
}

# get the value if its a tuple
val = fn :get, {:ok, v}, next -> next.(v)
          :get, data, next -> next.(data) end
# It works on the original map
get_in(map, ["category", val, "defaultValue"])
|> IO.inspect
# 10

# Also works on a preprocessed map
get_in(cleaned_map, ["category", val, "defaultValue"])
|> IO.inspect
# 10

Where Next?

Popular in Questions Top

LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New

We're in Beta

About us Mission Statement