Put_in/2 not working properly

Hello, I have I get a json response from an API, it has an array of length 1 (yes the array always have only one element), I want to change the value of this array to an empty map if it came as an empty array. Here is my code

if !Enum.empty?(json_res[:array]) do
   #some actions 
  else
      json_res = put_in(json_res[:array], Map.new())
end
#Some Actions

but it does not work, the json_res value of :array is still [].

Can you help me?
Thanks in Advance

1 Like

You are setting json_res in a do end block…

It will not be available to the outer scope.

You should do it like this…

json_res = if ... do
  ...
else
  ...
end
3 Likes
json_res =
  case Map.get(json_res, :array) do
    nil ->
      # Do something if there's no "array" key at all. Your code above didn't account for that.

    [] ->
      # Empty, let's put this new map in there.
      put_in(json_res, [:array], %{}) # Last parameter can be "Map.new", if you like that way better.

    _ ->
      # The "array" key points at something that's not nil or empty list, just return the original object.
      json_res
  end

A sample:

iex> x = %{array: []}
%{array: []}
iex> put_in x, [:array], %{}
%{array: %{}}

Not sure I understand you correctly though. Do you want to replace [] with %{} or do you want to put an empty map inside the empty list, making it not empty?


You have to stop thinking about FP languages like you do with JS, PHP, Python etc. Variables are NOT changed in place. You are transforming an object to a modified copy and then you assign the result to a new variable (or the same one, overwriting its contents).

1 Like

It’s less a FP vs. OOP topic, but elixir does have different lexical scoping than those languages. While people usually only expect e.g. function boundries to result in a new scope the same will happen in elixir for other expressions (most importantly if/case/cond) as well.

2 Likes

Of course. I found out that simplifying things initially for people who still struggle helps them get some understanding and translate it into a workable solution. :slight_smile:

1 Like

Also double check that your key value is actually an atom. Usually it will be a string for externally generated JSON, but you have an atom.

2 Likes

I use httpoison to parse it before doing so. thank you!

1 Like