LoginSignup
5
4

More than 3 years have passed since last update.

【Ruby】ハッシュとJSONの変換メモ

Posted at

前提

  • Ruby 2.7
  • Hash -> JSON は JSONモジュールの to_json を使用
  • JSON -> Hash は JSON.parse を使用

メモ

JSONはキーが文字列限定。Rubyのハッシュはキー、値ともに任意のオブジェクト。
ということは、RubyのハッシュからJSONに変換するときは、何らかのルールで、元のハッシュオブジェクトにJSONがサポートしていない型があった場合は変換されることとなる。

以前のメモ

JSONの形式の仕様ざっくりまとめとサンプル集 - Qiita https://qiita.com/kure/items/df04ca760290fd51b904

Rubyのハッシュの小さなサンプルメモ - Qiita https://qiita.com/kure/items/4f104bf4af4a5e243e61

サンプル

JSON -> Hash

キーは文字列のまま、値もそのまま変換される。null は nil へ。

require "json"

# JSON -> Hash
json1 = '{
  "name1": 0
}'

json2 = '{
  "name4": {
      "name5": 0
  }
}'

json3 = '{
  "name2": "value2"
}'

json4 = '{
  "name4": null
}'

pp JSON.parse(json1) # => {"name1"=>0}
pp JSON.parse(json2) # => {"name4"=>{"name5"=>0}}
pp JSON.parse(json3) # => {"name2"=>"value2"}
pp JSON.parse(json4) # => {"name4"=>nil}

Hash -> JSON

  • キー
    • 強制的に文字列に変換される。nil は空文字列として変換される。- - 値
    • シンボルやBoolean等はその文字のまま文字列として変換される。 Rubyのクラスやオブジェクト等、そのままではJSONに無い型は文字列として変換されるもよう。
# Hash -> JSON

class Test; end

hash1 = { 0 => 1 }
pp hash1.to_json # => "{\"0\":1}"

hash2 = { "name" => "value" }
pp hash2.to_json # => "{\"name\":\"value\"}"

hash3 = { true => "false_str" }
pp hash3.to_json # => "{\"true\":\"false_str\"}"

hash4 = { name: "value" }
pp hash4.to_json # => "{\"name\":\"value\"}"

hash5 = { nil => nil }
pp hash5.to_json #=> "{\"\":null}"

hash6 = { "class" => Class }
pp hash6.to_json # => "{\"class\":\"Class\"}"

hash7 = { "class" => Test }
pp hash7.to_json # => "{\"class\":\"Test\"}"

hash8 = { "bool" => true }
pp hash8.to_json # => "{\"bool\":true}"

hash9 = {Class => Class}
pp hash9.to_json # => "{\"Class\":\"Class\"}"
5
4
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
5
4