Convert camel case to underscore in json

Hi

In the company that I work for, have an api naming convention for json rest api which includes camel case not underscore. Like this

{
“someResource”: {
“userId”: 1,

}
}

I’m using Phoenix and for it to be easy to use Ecto 2 changeset, I want it to be convert to user_id so that cast function will just work.
What is the preferred way of doing this?

For reference, previously in Java we would have done this

class SomeResoure {
@JsonProperty(“userId”)
private Long user_id;
}

1 Like

To translate something from CamelCase or dromedarisCase to snake_case, we have the Macro.underscore/1 function. There also is a Macro.camel_case/1 to translate snake_case back to CamellCase. I am not sure id there exists a method to go back to dromedarisCase, but adapting it from Macro.camel_case/1 is of course trivial.

4 Likes

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 snake_case.

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

  1. add this line to mix.exs into deps: {:recase, "~> 0.1"}
  2. run mix deps.get

That’s how you use it:

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

Recase.to_snake("someValue")
# => "some_value"

You can find docs here: Recase — recase v0.7.0
And the repo here: GitHub - wemake-services/recase: ♻ Convert strings to any case.

2 Likes