将snake_case键控映射转换为ellir,phoenix中的camelCase键控映射,然后将内容作为JSON发送

时间:2016-06-17 11:19:58

标签: elixir phoenix-framework

我希望在将内容作为JSON发送之前,将elixir中的地图键从snake case更改为camel case。我怎样才能做到这一点?它应该只是一个函数,我将包装每个响应,还是应该在较低级别,即在毒药中完成?

由于

3 个答案:

答案 0 :(得分:16)

许多人不知道这是内置于Elixir:

iex> Macro.underscore "SAPExample"
"sap_example"

iex> Macro.camelize "sap_example"
"SapExample"

iex> Macro.camelize "hello_10"
"Hello10"

参见文档:http://elixir-lang.org/docs/stable/elixir/Macro.html#underscore/1

实施:https://github.com/elixir-lang/elixir/blob/master/lib/elixir/lib/macro.ex#L1192

答案 1 :(得分:3)

有人可能会使用Macro.underscore/1,但这不是正确的做法。由于Macro模块本身states

  

此功能旨在强调语言标识符/令牌,     这就是它属于Macro模块的原因。不要将它作为一般用途     用于强调字符串的机制,因为它不支持Unicode或     在Elixir标识符中无效的字符。

因此,最好使用其他一些库。我建议使用recase。它可以将字符串转换为任何大小写,而不仅仅是camelCase

由于它是第三方库,您需要安装它。

  1. 将此行添加到mix.exs deps{:recase, "~> 0.1"}
  2. 运行mix deps.get
  3. 这就是你如何使用它:

    Recase.to_camel("some-value")
    # => "someValue"
    
    Recase.to_camel("Some Value")
    # => "someValue"
    

    您可以在此处找到文档:https://hexdocs.pm/recase/readme.html

    这里的回购:https://github.com/sobolevn/recase

答案 2 :(得分:1)

使用Inflex库要好得多:https://github.com/nurugger07/inflex#underscore

iex> Inflex.underscore("camelCase")
"camel_case"