Skip to content

Commit 4922d2a

Browse files
committed
Check for existence of #to_json method before call
1 parent 4dec168 commit 4922d2a

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

lib/json/pure/generator.rb

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,11 @@ def json_transform(state)
363363
result << state.space_before
364364
result << ':'
365365
result << state.space
366-
result << value.to_json(state)
366+
if value.respond_to?(:to_json)
367+
result << value.to_json(state)
368+
else
369+
result << %{"#{String(value)}"}
370+
end
367371
first = false
368372
}
369373
depth = state.depth -= 1
@@ -398,7 +402,11 @@ def json_transform(state)
398402
each { |value|
399403
result << delim unless first
400404
result << state.indent * depth if indent
401-
result << value.to_json(state)
405+
if value.respond_to?(:to_json)
406+
result << value.to_json(state)
407+
else
408+
result << %{"#{String(value)}"}
409+
end
402410
first = false
403411
}
404412
depth = state.depth -= 1

tests/test_json_generate.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ def to_s; self; end
342342
undef to_json
343343
end
344344
assert_nothing_raised(SystemStackError) do
345-
assert_equal '[""]', JSON.generate([s.new])
345+
assert_equal '["foo"]', JSON.generate([s.new('foo')])
346346
end
347347
end
348348
end

0 commit comments

Comments
 (0)