Skip to content

End of Life Ruby 3.2 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

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)
See also #fast_generate #load #dump #load_file also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0