Ruby 4.1 リファレンスマニュアル

instance method JSON::GeneratorMethods#to_json

to_json(state_or_hash = nil) -> StringRuby 4.1 から[permalink][rdoc][edit]

自身から生成した JSON 形式の文字列を返します。

自身が nil、true、false、IntegerFloatArrayHash のいずれかである場合は、それに対応する JSON の値に変換します。 String は JSON の文字列に変換します。それ以外のオブジェクトは to_s で文字列にした結果を JSON の文字列に変換します。このため、独自のクラスのインスタンスを構造を持った JSON にしたい場合は、そのクラスで to_json を定義する必要があります。

[PARAM] state_or_hash:
生成する JSON 形式の文字列をカスタマイズするために JSON::State のインスタンスか、 JSON::State.new の引数と同じ Hash を指定します。
require "json"

p [1, 2, 3].to_json                          # => "[1,2,3]"
p({ "name" => "tanaka", "age" => 19 }.to_json) # => "{\"name\":\"tanaka\",\"age\":19}"
p 10.to_json                                 # => "10"
p 1.0.to_json                                # => "1.0"
p nil.to_json                                # => "null"
p true.to_json                               # => "true"
p "test".to_json                             # => "\"test\""
p [1, { a: 1 }].to_json(space: " ")          # => "[1,{\"a\": 1}]"
例: 独自クラスの to_json
require "json"

class Point
  def initialize(x, y)
    @x, @y = x, y
  end

  def to_s
    "(#{@x}, #{@y})"
  end
end

p Point.new(1, 2).to_json # => "\"(1, 2)\""

class Point
  def to_json(*args)
    { "x" => @x, "y" => @y }.to_json(*args)
  end
end

p Point.new(1, 2).to_json # => "{\"x\":1,\"y\":2}"
p [Point.new(1, 2)].to_json # => "[{\"x\":1,\"y\":2}]"

[SEE_ALSO] JSON?.generate, JSON::State