Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
JSON#generate
(::_ToJson obj, ?::JSON::options opts) -> ::String
JSON.generate(obj, opts = nil) → new_string
ext/json/lib/json/common.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.4.1/ext/json/lib/json/common.rb, line 301
def generate(obj, opts = nil)
if State === opts
opts.generate(obj)
else
State.generate(obj, opts, nil)
end
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)