Skip to content

Commit e2e9936

Browse files
YuheiNakasakabyroot
authored andcommitted
Fix behavior of trying to parse non-string objects
1 parent 54b5f2b commit e2e9936

File tree

2 files changed

+40
-8
lines changed

2 files changed

+40
-8
lines changed

lib/json/common.rb

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,16 @@ class << self
2020
# ruby = [0, 1, nil]
2121
# JSON[ruby] # => '[0,1,null]'
2222
def [](object, opts = {})
23-
if object.respond_to? :to_str
24-
JSON.parse(object.to_str, opts)
25-
else
26-
JSON.generate(object, opts)
23+
if object.is_a?(String)
24+
return JSON.parse(object, opts)
25+
elsif object.respond_to?(:to_str)
26+
str = object.to_str
27+
if str.is_a?(String)
28+
return JSON.parse(object.to_str, opts)
29+
end
2730
end
31+
32+
JSON.generate(object, opts)
2833
end
2934

3035
# Returns the JSON parser class that is used by JSON. This is either
@@ -693,11 +698,16 @@ def jj(*objs)
693698
# The _opts_ argument is passed through to generate/parse respectively. See
694699
# generate and parse for their documentation.
695700
def JSON(object, *args)
696-
if object.respond_to? :to_str
697-
JSON.parse(object.to_str, args.first)
698-
else
699-
JSON.generate(object, args.first)
701+
if object.is_a?(String)
702+
return JSON.parse(object, args.first)
703+
elsif object.respond_to?(:to_str)
704+
str = object.to_str
705+
if str.is_a?(String)
706+
return JSON.parse(object.to_str, args.first)
707+
end
700708
end
709+
710+
JSON.generate(object, args.first)
701711
end
702712
end
703713

test/json/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

@@ -129,6 +150,7 @@ def test_dump_should_modify_defaults
129150

130151
def test_JSON
131152
assert_equal @json, JSON(@hash)
153+
assert_equal @json, JSON(@hash_with_method_missing)
132154
assert_equal @hash, JSON(@json)
133155
end
134156

0 commit comments

Comments
 (0)