instance method
JSON#dump
(::_ToJson obj, ?::Integer limit) -> ::String
(::_ToJson obj, ::JSON::_WritableIO anIO) -> ::JSON::_Write
(::_ToJson obj, ::JSON::_Write anIO, ?::Integer limit) -> ::JSON::_Write
JSON.dump(obj, io = nil, limit = nil)
ext/json/lib/json/common.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.0.0/ext/json/lib/json/common.rb, line 930
def dump(obj, anIO = nil, limit = nil, kwargs = nil)
if kwargs.nil?
if limit.nil?
if anIO.is_a?(Hash)
kwargs = anIO
anIO = nil
end
elsif limit.is_a?(Hash)
kwargs = limit
limit = nil
end
end
unless anIO.nil?
if anIO.respond_to?(:to_io)
anIO = anIO.to_io
elsif limit.nil? && !anIO.respond_to?(:write)
anIO, limit = nil, anIO
end
end
opts = JSON._dump_default_options
opts = opts.merge(:max_nesting => limit) if limit
opts = opts.merge(kwargs) if kwargs
begin
State.generate(obj, opts, anIO)
rescue JSON::NestingError
raise ArgumentError, "exceed depth limit"
end
end
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 methodwrite; the JSON String is written toio, andiois returned. Ifiois not given, the JSON String is returned. -
Argument
limit, if given, is passed toJSON.generateas optionmax_nesting.
When argument io is not given, returns the JSON String generated from obj:
Example
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:
Example
path = 't.json' File.open(path, 'w') do |file| JSON.dump(obj, file) end # => #<File:t.json (closed)> puts File.read(path)
Output:
Example
{"foo":[0,1],"bar":{"baz":2,"bat":3},"bam":"bad"}
See also
.on_mixed_keys_hash
#fast_generate
.deprecated_singleton_attr_accessor
#generate
also in
4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0