0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Rails | Convert all hash keys from symbol to string (stringify_keys / deep_stringify_keys)

Last updated at Posted at 2019-04-16

As the title.

 { a: 1, b: 2, c: 3 }.stringify_keys # => {"a"=>1, "b"=>2, "c"=>3} 

When the hierarchy of hash is deep

deep_stringify_keys it is deep_stringify_keys , it will change to all symbols regardless of the hierarchy. (Rails 4)

 { a: 1, b: 2, c: { d: 3 } }.deep_stringify_keys # => {"a"=>1, "b"=>2, "c"=>{"d"=>3}} 

Wow deep stringify keys

deep_stringify_keys , for example, even if there is an array in the middle, it does not matter.

 { a:1, b: 2, c: [{ d: [ { e:3 }] } ] }.deep_stringify_keys # => {"a"=>1, "b"=>2, "c"=>[{"d"=>[{"e"=>3}]}]} 

Supplement

  • There is also a destructive method. ( stringify_keys! / deep_stringify_keys! )
  • stringify instead of stringfy. Be careful with typos.
  • I posted it because I didn't hit it with "Rails / All / Symbols / Strings".

environment

  • Rails 4.2.6

Original by

Rails | ハッシュのキーを全てシンボルから文字列に変える ( stringify_keys / deep_stringify_keys )

About

About this translattion

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?