Convert snake_case memory card to CamelCase card with key in elixir, phoenix before sending material as JSON

I want to change the card keys in the elixir from the case of a snake to a camel, before sending the material in the form of JSON. How can i do this? Should it just be a function in which I will wrap each answer or should it be done at some lower level, i.e. in Poison?

thanks

+6
source share
3 answers

Many do not 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 Docs: http://elixir-lang.org/docs/stable/elixir/Macro.html#underscore/1

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

+15
source

You can use Macro.underscore/1 , but this is not the right way to do this. Since the Macro module itself states :

This feature was designed to emphasize language identifiers / tokens, so it belongs to the Macro module. Do not use it as a general underline mechanism, as it does not support Unicode or characters that are not allowed in Elixir identifiers.

So it’s better to use a different library. I would recommend using recase . It can convert a string anyway, not just camelCase .

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

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

Here's how you use it:

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

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

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

+5
source

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

 iex> Inflex.underscore("camelCase") "camel_case" 
+1
source

All Articles