Skip to content

Commit f675bd9

Browse files
committed
Fix behavior of trying to parse non-string objects
1 parent 5d9d8f3 commit f675bd9

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

lib/json/common.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class << self
1616
# ruby = [0, 1, nil]
1717
# JSON[ruby] # => '[0,1,null]'
1818
def [](object, opts = {})
19-
if object.respond_to? :to_str
19+
if object.respond_to?(:to_str) && object.to_str.is_a?(String)
2020
JSON.parse(object.to_str, opts)
2121
else
2222
JSON.generate(object, opts)
@@ -683,7 +683,7 @@ def jj(*objs)
683683
# The _opts_ argument is passed through to generate/parse respectively. See
684684
# generate and parse for their documentation.
685685
def JSON(object, *args)
686-
if object.respond_to? :to_str
686+
if object.respond_to?(:to_str) && object.to_str.is_a?(String)
687687
JSON.parse(object.to_str, args.first)
688688
else
689689
JSON.generate(object, args.first)

tests/json_common_interface_test.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,13 @@
66
class JSONCommonInterfaceTest < Test::Unit::TestCase
77
include JSON
88

9+
module MethodMissing
10+
def method_missing(name, *args); end
11+
def respond_to_missing?(name, include_private)
12+
true
13+
end
14+
end
15+
916
def setup
1017
@hash = {
1118
'a' => 2,
@@ -17,12 +24,26 @@ def setup
1724
'h' => 1000.0,
1825
'i' => 0.001
1926
}
27+
28+
@hash_with_method_missing = {
29+
'a' => 2,
30+
'b' => 3.141,
31+
'c' => 'c',
32+
'd' => [ 1, "b", 3.14 ],
33+
'e' => { 'foo' => 'bar' },
34+
'g' => "\"\0\037",
35+
'h' => 1000.0,
36+
'i' => 0.001
37+
}
38+
@hash_with_method_missing.extend MethodMissing
39+
2040
@json = '{"a":2,"b":3.141,"c":"c","d":[1,"b",3.14],"e":{"foo":"bar"},'\
2141
'"g":"\\"\\u0000\\u001f","h":1000.0,"i":0.001}'
2242
end
2343

2444
def test_index
2545
assert_equal @json, JSON[@hash]
46+
assert_equal @json, JSON[@hash_with_method_missing]
2647
assert_equal @hash, JSON[@json]
2748
end
2849

@@ -121,6 +142,7 @@ def test_dump_should_modify_defaults
121142

122143
def test_JSON
123144
assert_equal @json, JSON(@hash)
145+
assert_equal @json, JSON(@hash_with_method_missing)
124146
assert_equal @hash, JSON(@json)
125147
end
126148

0 commit comments

Comments
 (0)