Help us understand the problem. What is going on with this article?

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

前提

  • 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\"}"
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away