Elixir - 更新包含字符串键

时间:2018-05-22 08:54:42

标签: elixir elixir-framework

如何更新包含字符串键的地图?我想更新"品牌"值。

我的代码(产品是带有"品牌"键的地图):

  brand = URI.decode(product["brand"])
  IO.inspect(brand, label: "uri decode")
  brand = elem(Poison.decode(brand), 1)
  IO.inspect(brand, label: "json decode")
  Map.put(product, "brand", brand)
  IO.inspect(product["brand"], label: "actual product brand")

输出:

uri decode: "\"e&ggsssssaaqss\""
json decode: "e&ggsssssaaqss"
actual product brand: "%22e%26ggsssssaaqss%22"

它没有更新product["brand"]

actual product brand日志如果更新,则应该等于json decode日志。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

如果地图的字符串键如此:

my_map = %{"a" => 1, "b" => 2}

您可以使用更改后的密钥创建新地图,如下所示:

my_new_map = Map.put(my_map, "a", 100)

或者您可以使用更新的地图重新绑定现有的my_map变量,如下所示:

my_map = Map.put(my_map, "a", 100)

答案 1 :(得分:0)

更简洁的语法是|操作

my_map = %{"a" => 1, "b" => 2}
%{my_map | "a" => 100}

或者您也可以使用put_in方法

my_map = %{"a" => 1, "b" => 2}
put_in(my_map["a"], 100)