olosegres/jsona

Deserialize `snake_case` to `camelCase`

abiggy opened this issue · 1 comments

Using jsona for speedy deserializing of our jsonapi! And was particularly interested in this related issue that was resolved: #1

Issue

I want to deserialize snake_case property names to camelCase

However it seems that jsona currently only handles jsonapi's kebab-case names but from what I understand of the jsonapi spec (https://jsonapi.org/format/#document-member-names) member names are allowed to be snake_case:

Additionally, the following characters are allowed in member names, except as the first or last character:

  • U+002D HYPHEN-MINUS, “-“
  • U+005F LOW LINE, “_”
  • U+0020 SPACE, “ “ (not recommended, not URL safe)

The API I am working with has all of its attributes in snake_case.

What I find strange is that this behaviour in jsona is intentional, as it is verified that snake_case does not become camelCase via test coverage here:

expect(model['foo_bar']).to.be.equal(5);
Wondering what the reason is for this?

Possible Solution:

By changing this line here:

const camelizedType = type.replace(/-([a-z0-9])/g, function (g) { return g[1].toUpperCase(); });

to something like:

const camelizedType = type.replace(/(-|_)([a-z0-9])/g, function (g) { return g[1].toUpperCase(); });

handles the snake_case member names!

Demo

I have put together a tiny demo of it here that console.logs the result of the deserializing:

https://codesandbox.io/s/ppy60ykz3j?fontsize=14

Added a bit of a post-processing to do the modification myself to get everything to camelCase but I feel it's not optimal that I have to do this.

Hi!
It's not supported because there was no need for this function.

If you made a PR that updates switchCasePropertyMappers.ts and tests, I will release new version of package :)