Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
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, _deprecated_limit = nil, options = nil)
ext/json/lib/json/common.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.1.0-preview1/ext/json/lib/json/common.rb, line 744
def dump(obj, anIO = nil, _deprecated_limit = nil, kwargs = nil)
if kwargs.nil?
if _deprecated_limit.nil?
if anIO.is_a?(Hash)
kwargs = anIO
anIO = nil
end
elsif _deprecated_limit.is_a?(Hash)
kwargs = _deprecated_limit
_deprecated_limit = nil
end
end
unless anIO.nil?
if anIO.respond_to?(:to_io)
anIO = anIO.to_io
elsif _deprecated_limit.nil? && !anIO.respond_to?(:write)
anIO, _deprecated_limit = nil, anIO
end
end
opts = {
allow_nan: !(kwargs && kwargs[:rfc8785]),
}
opts[:max_nesting] = _deprecated_limit if _deprecated_limit
opts.merge!(kwargs) if kwargs
State.generate(obj, opts, anIO)
end
Dumps obj as a JSON string, i.e. calls generate on the object and returns the result.
-
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
_deprecated_limitis deprecated, pass the:max_nestingoption instead.
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"}