Skip to main content

Command Palette

Search for a command to run...

[Rails] Camelize and underscore Hash/JSON keys

Published
2 min read

While the snake case Hash keys are conventionally used in Ruby world, sometimes we prefer camel case keys in the front end. Here is my note on how to handle this problem.

Camelizing keys of outgoing JSON data

A: using Hash#deep_transform_keys!

hash.deep_transform_keys! { |key| key.camelize(:lower) }

B: using jbuilder

  • Automatically camelize the keys of any outgoing JSON data.
# config/environment.rb
Jbuilder.key_format camelize: :lower

Snakecasing keys of incoming JSON data

A: using Hash#deep_transform_keys!

hash.deep_transform_keys! { |key| key.underscore }

B: in a custom middleware

  • Automatically snakecase the keys of any incoming params.
# application.rb
require_relative "../app/middlewares/snake_case_parameters"
config.middleware.use SnakeCaseParameters
# app/middlewares/snake_case_parameters.rb
# A middleware that underscores the keys of any incoming (to the rails server) params
class SnakeCaseParameters
  def initialize(app)
    @app = app
  end

  def call(env)
    request = ActionDispatch::Request.new(env)
    request.request_parameters.deep_transform_keys!(&:underscore)
    request.query_parameters.deep_transform_keys!(&:underscore)

    @app.call(env)
  end
end

Resources

  • https://apidock.com/rails/Hash/transform_keys
  • https://apidock.com/rails/Hash/deep_transform_keys
  • https://stackoverflow.com/questions/37569439/automatically-convert-hash-keys-to-camelcase-in-jbuilder

More from this blog

Raspberry Pi TensorFlow Liteで物体検出を楽しむ

この記事について Raspberry Pi、TensorFlow、Pythonのいずれにも詳しくない筆者が、物体検出をやって楽しんだ成果の記録です。 TensorFlow公式の物体検出のサンプルプログラムを実行します。 動作環境 ボード Raspberry Pi 4 Model B OS Raspberry Pi OS (32-bit または 64-bit) デスクトップ環境 カメラ Raspberry Pi カメラモジュール v2 Python Python ...

Apr 23, 20231 min read

Elixir Circuits.I2C with Mox

This is written in Japanese. I might convert it to English later, maybe. はじめに Elixirのテストでモックを用意するときに利用するElixirパッケージとして、moxが人気です。Elixir作者のJosé Valimさんが作ったからということもありますが、ただモックを用意するだけではなくElixirアプリの構成をより良くするためのアイデアにまで言及されているので、教科書のようなものと思っています。 一言でいうと「その場...

Dec 3, 20213 min read
M

Masatoshi Nishiguchi's Blog

62 posts

[Rails] Camelize and underscore Hash/JSON keys