convert snake_case keyed map to camelCase keyed map in elixir, phoenix before sending stuff as JSON

Many don't know that this is built-into Elixir:

iex> Macro.underscore "SAPExample"
"sap_example"

iex> Macro.camelize "sap_example"
"SapExample"

iex> Macro.camelize "hello_10"
"Hello10"

See Macro.underscore/1 docs or the implementation


One might use Macro.underscore/1, but that's not correct way to do it. Since the Macro module itself states:

This function was designed to underscore language identifiers/tokens, that's why it belongs to the Macro module. Do not use it as a general mechanism for underscoring strings as it does not support Unicode or characters that are not valid in Elixir identifiers.

So, it is better to use some other library. I would recommend to use recase. It can convert string to any case, not just camelCase.

Since it is a third-party library you need to install it.

  1. add this line to mix.exs into deps: {:recase, "~> 0.6"} Make sure to use the latest version!
  2. run mix deps.get

That's how you use it:

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

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

You can find docs here: https://hexdocs.pm/recase/readme.html

And the repo here: https://github.com/sobolevn/recase


Much better to use the Inflex library: https://github.com/nurugger07/inflex#underscore

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