我有message = %{"to" => "testuser", "value" => "asdads"}
地图。我需要访问"以及#34;这张地图中的关键
message.to
message[:to]
Map.fetch!(message, to)
到目前为止没有任何工作
这是控制台错误消息
[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>}
答案 0 :(得分:5)
你的地图键是字符串,而不是原子。您发布的所有三个代码段都将访问密钥:to
(atom),而不是"to"
(字符串)。
您可以message["to"]
来访问该值。如果您想在价值不存在时提出错误,也可以Map.fetch!(message, "to")
。
答案 1 :(得分:0)
你可以这样做
case Map.fetch(message,"to") do
{:ok, value} -> IO.inspect value; #Success
:error -> IO.inspect "Key Not found" #Error
end