End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
JSON#generate
JSON.generate(obj, opts = nil) → new_string
ext/json/lib/json/common.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.1.3/ext/json/lib/json/common.rb, line 296
def generate(obj, opts = nil)
if State === opts
state, opts = opts, nil
else
state = State.new
end
if opts
if opts.respond_to? :to_hash
opts = opts.to_hash
elsif opts.respond_to? :to_h
opts = opts.to_h
else
raise TypeError, "can't convert #{opts.class} into Hash"
end
state = state.configure(opts)
end
state.generate(obj)
end
Returns a String containing the generated JSON data.
See also JSON.fast_generate, JSON.pretty_generate.
Argument obj is the Ruby object to be converted to JSON.
Argument opts, if given, contains a Hash of options for the generation. See Generating Options.
When obj is an Array, returns a String containing a JSON array:
Example
obj = ["foo", 1.0, true, false, nil] json = JSON.generate(obj) json # => '["foo",1.0,true,false,null]'
When obj is a Hash, returns a String containing a JSON object:
Example
obj = {foo: 0, bar: 's', baz: :bat} json = JSON.generate(obj) json # => '{"foo":0,"bar":"s","baz":"bat"}'
For examples of generating from other Ruby objects, see Generating JSON from Other Objects.
Raises an exception if any formatting option is not a String.
Raises an exception if obj contains circular references:
Example
a = []; b = []; a.push(b); b.push(a) # Raises JSON::NestingError (nesting of 100 is too deep): JSON.generate(a)