Method: JSON.pretty_generate
- Defined in:
- lib/json/common.rb
.pretty_generate(obj, opts = nil) ⇒ Object
:call-seq:
JSON.pretty_generate(obj, opts = nil) -> new_string
Arguments obj and opts here are the same as arguments obj and opts in JSON.generate.
Default options are:
{
indent: ' ', # Two spaces
space: ' ', # One space
array_nl: "\n", # Newline
object_nl: "\n" # Newline
}
Example:
obj = {foo: [:bar, :baz], bat: {bam: 0, bad: 1}}
json = JSON.pretty_generate(obj)
puts json
Output:
{
"foo": [
"bar",
"baz"
],
"bat": {
"bam": 0,
"bad": 1
}
}
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 |
# File 'lib/json/common.rb', line 507 def pretty_generate(obj, opts = nil) return opts.generate(obj) if State === opts = 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 = .merge(opts) end State.generate(obj, , nil) end |