diff --git a/CHANGES.md b/CHANGES.md index 19d7d51e..2e3f7ec3 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,8 @@ ### Unreleased +* Restore the `limit` positional argument of `JSON.dump`. + ### 2026-09-07 (3.0.0) * Add `JSON::ParserError#json_path` to locate parse errors in the document as a JSONPath-style string (e.g. `$.foo[0].bar`). For duplicate key errors it points at the duplicated key itself. diff --git a/lib/json/common.rb b/lib/json/common.rb index 34dc123b..f8b68e5f 100644 --- a/lib/json/common.rb +++ b/lib/json/common.rb @@ -726,16 +726,14 @@ def load(source, proc = nil, allow_blank: true, **options) end # :call-seq: - # JSON.dump(obj, io = nil, options = nil) + # JSON.dump(obj, io = nil, _deprecated_limit = nil, options = 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 +_deprecated_limit+ is deprecated, pass the +:max_nesting+ option instead. # --- # # When argument +io+ is not given, returns the \JSON \String generated from +obj+: @@ -751,21 +749,31 @@ def load(source, proc = nil, allow_blank: true, **options) # puts File.read(path) # Output: # {"foo":[0,1],"bar":{"baz":2,"bat":3},"bam":"bad"} - def dump(obj, anIO = nil, kwargs = nil) + def dump(obj, anIO = nil, _deprecated_limit = nil, kwargs = nil) if kwargs.nil? - if anIO.is_a?(Hash) - kwargs = anIO - anIO = 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 - if anIO&.respond_to?(:to_io) - anIO = anIO.to_io + 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: true, } + opts[:max_nesting] = _deprecated_limit if _deprecated_limit opts.merge!(kwargs) if kwargs State.generate(obj, opts, anIO) diff --git a/test/json/json_generator_test.rb b/test/json/json_generator_test.rb index 2a64a5e7..b0df70d5 100755 --- a/test/json/json_generator_test.rb +++ b/test/json/json_generator_test.rb @@ -86,6 +86,12 @@ def test_dump_strict assert_equal '{"hello":"world"}', dump({ hello: :world }, strict: true) end + def test_dump_deprecated_limit + io = StringIO.new + JSON.dump([1], io, 0) + assert_equal '[1]', io.string + end + def test_not_frozen [ [[], '[]'],