instance method
JSON#pretty_generate
(::_ToJson obj, ?::JSON::options opts) -> untyped
JSON.pretty_generate(obj, opts = nil) → new_string
ext/json/lib/json/common.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.0.0/ext/json/lib/json/common.rb, line 507
def pretty_generate(obj, opts = nil)
return opts.generate(obj) if State === opts
options = PRETTY_GENERATE_OPTIONS
if opts
unless opts.is_a?(Hash)
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
end
options = options.merge(opts)
end
State.generate(obj, options, nil)
end
Arguments obj and opts here are the same as arguments obj and opts in JSON.generate.
Default options are:
Example
{
indent: ' ', # Two spaces
space: ' ', # One space
array_nl: "\n", # Newline
object_nl: "\n" # Newline
}
Example:
Example
obj = {foo: [:bar, :baz], bat: {bam: 0, bad: 1}} json = JSON.pretty_generate(obj) puts json
Output:
Example
{
"foo": [
"bar",
"baz"
],
"bat": {
"bam": 0,
"bad": 1
}
}