简体   繁体   English

我如何在phoenix elixir框架中访问map内部的值

[英]How can i access value inside map in phoenix elixir framework

I have message = %{"to" => "testuser", "value" => "asdads"} map. 我有message = %{"to" => "testuser", "value" => "asdads"}映射。 I need to access value of "to" key inside this map 我需要访问此映射内的“ to”键的值

message.to
message[:to]
Map.fetch!(message, to)

nothing work so far 到目前为止没有任何工作

this is the console error message 这是控制台错误消息

[error] GenServer #PID<0.395.0> terminating
** (KeyError) key :to not found in: %{"to" => "testuser", "value" => "aadadadad"}
    (phoenix_chat) web/channels/room_channel.ex:31: PhoenixChat.RoomChannel.handle_in/3
    (phoenix) lib/phoenix/channel/server.ex:225: anonymous fn/4 in Phoenix.Channel.Server.handle_info/2
    (stdlib) gen_server.erl:601: :gen_server.try_dispatch/4
    (stdlib) gen_server.erl:667: :gen_server.handle_msg/5
    (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Last message: %Phoenix.Socket.Message{event: "message:new", payload: %{"to" => "testuser", "value" => "aadadadad"}, ref: "4", topic: "room:Pamidu"}
State: %Phoenix.Socket{assigns: %{user: "Pamidu"}, channel: PhoenixChat.RoomChannel, channel_pid: #PID<0.395.0>, endpoint: PhoenixChat.Endpoint, handler: PhoenixChat.UserSocket, id: nil, joined: true, pubsub_server: PhoenixChat.PubSub, ref: nil, serializer: Phoenix.Transports.WebSocketSerializer, topic: "room:Pamidu", transport: Phoenix.Transports.WebSocket, transport_name: :websocket, transport_pid: #PID<0.384.0>}

Your map's keys are strings, not atoms. 地图的键是字符串,而不是原子。 All the three code snippets you posted will access the key :to (atom), not "to" (string). 您发布的所有三个代码段都将访问键:to (原子),而不是"to" (字符串)。

You can do message["to"] to access the value. 您可以执行message["to"]来访问该值。 You can also do Map.fetch!(message, "to") if you want to raise an error if the value doesn't exist. 如果您想在错误值不存在的情况下引发错误Map.fetch!(message, "to")也可以执行Map.fetch!(message, "to")

You could do like below 你可以像下面这样

case Map.fetch(message,"to") do
   {:ok, value} -> IO.inspect value;           #Success  
   :error       -> IO.inspect "Key Not found"  #Error
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM