my coredump

自分用の公開メモです。主にプログラムのこととか書くはず。

RubyのJSON.parseでキーをシンボルにする

symbolize_namestrueにすればよかった。

リクエストできたハッシュと内部で持ってたハッシュをマージした後に色々やってて「なんかおかしいなー」と思ったらハッシュのキーが文字列とシンボルでずれてた… 10分くらいハマってた…

余談だけどpryが便利で良い。
JS書くときとかブラウザのコンソールで色々試しながら書いてておかげで捗るけど、それに近い感じでできる。ドキュメントとかもその場で見れるのでさらに便利。

$ pry
[1] pry(main)> ri JSON.parse
JSON.parse

(from ruby core)
------------------------------------------------------------------------------
  parse(source, opts = {})

------------------------------------------------------------------------------

Parse the JSON document source into a Ruby data structure and return
it.

opts can have the following keys:
* max_nesting: The maximum depth of nesting allowed in the parsed data
  structures. Disable depth checking with :max_nesting => false. It defaults
  to 100.
* allow_nan: If set to true, allow NaN, Infinity and -Infinity in
  defiance of RFC 4627 to be parsed by the Parser. This option defaults to
  false.
* symbolize_names: If set to true, returns symbols for the names (keys)
  in a JSON object. Otherwise strings are returned. Strings are the default.
* create_additions: If set to false, the Parser doesn't create
  additions even if a matching class and create_id was found. This option
  defaults to true.
* object_class: Defaults to Hash
* array_class: Defaults to Array

仰せのままに。

[2] pry(main)> str = '{"a": 1, "b": 2, "c": 3}'
=> "{\"a\": 1, \"b\": 2, \"c\": 3}"
[3] pry(main)> JSON.parse(str)
=> {"a"=>1, "b"=>2, "c"=>3}
[4] pry(main)> JSON.parse(str, {symbolize_names: true})
=> {:a=>1, :b=>2, :c=>3}

便利。