映射以elinix中的@开头的关键字

T. *_*one 2 elixir

我正在编写一些将发出HTTP POST请求的Elixir代码,其中正文是选项的JSON文档.其中一个属性以@符号开头.

不可能:

json = %{ q: "foobar", @timestamp: 1234567890 } |> Poison.encode!
Run Code Online (Sandbox Code Playgroud)

编写以@?开头的地图密钥文字的正确方法是什么?

Gaz*_*ler 6

如果您希望将其视为原子,您可以:

%{ :q => "foobar", :"@timestamp" => 1234567890 }
Run Code Online (Sandbox Code Playgroud)

这也是有效的:

json = %{ :"@timestamp" => 1234567890, q: "foobar" }
Run Code Online (Sandbox Code Playgroud)

然而,这不是:

json = %{ q: "foobar", :"@timestamp" => 1234567890 }
** (SyntaxError) iex:5: syntax error before: "@timestamp"
Run Code Online (Sandbox Code Playgroud)

您还可以使用字符串作为键:

json = %{ "@timestamp" => 1234567890, q: "foobar" }
Run Code Online (Sandbox Code Playgroud)