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.

jbuilderでマルチバイトや数字の名前(key)を使う

Last updated at Posted at 2023-10-27

はじめに

Railsでコードを書いているときに、レスポンスのJSONに日本語や数字で始まるキーを返さなくてはいけなくなりまたした。

こんな感じ↓

{
  "日本語のキー": "値",
  "12345": 12345
}

方法を探したのですが、検索の仕方が悪いせいか結論にたどり着くまでに結構苦労したので、備忘録代わりに結果を残しておきます。

結論

数字も日本語も全部これでOKです。set!最強!

json.set! :日本語のキー, '値'
json.set! :'12345', 12345

もう1つの方法

日本語だけなら直接 json. の後に書けます。
ただし RuboCop を使っていると Naming/AsciiIndentifiers というので警告が出ます。

json.日本語のキー '値'
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?