Method: JSON.dump

Defined in:
lib/json/common.rb

.dump(obj, anIO = nil, limit = nil) ⇒ Object

:call-seq:

JSON.dump(obj, io = nil, limit = nil)

Dumps obj as a JSON string, i.e. calls generate on the object and returns the result.

The default options can be changed via method JSON.dump_default_options.

  • Argument io, if given, should respond to method write; the JSON String is written to io, and io is returned. If io is not given, the JSON String is returned.

  • Argument limit, if given, is passed to JSON.generate as option max_nesting.


When argument io is not given, returns the JSON String generated from obj:

obj = {foo: [0, 1], bar: {baz: 2, bat: 3}, bam: :bad}
json = JSON.dump(obj)
json # => "{\"foo\":[0,1],\"bar\":{\"baz\":2,\"bat\":3},\"bam\":\"bad\"}"

When argument io is given, writes the JSON String to io and returns io:

path = 't.json'
File.open(path, 'w') do |file|
  JSON.dump(obj, file)
end # => #<File:t.json (closed)>
puts File.read(path)

Output:

{"foo":[0,1],"bar":{"baz":2,"bat":3},"bam":"bad"}


631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
# File 'lib/json/common.rb', line 631

def dump(obj, anIO = nil, limit = nil)
  if anIO and limit.nil?
    anIO = anIO.to_io if anIO.respond_to?(:to_io)
    unless anIO.respond_to?(:write)
      limit = anIO
      anIO = nil
    end
  end
  opts = JSON.dump_default_options
  opts = opts.merge(:max_nesting => limit) if limit
  result = generate(obj, opts)
  if anIO
    anIO.write result
    anIO
  else
    result
  end
rescue JSON::NestingError
  raise ArgumentError, "exceed depth limit"
end