Skip to content

Commit

Permalink
Fix behavior of trying to parse non-string objects
Browse files Browse the repository at this point in the history
  • Loading branch information
YuheiNakasaka authored and byroot committed Oct 17, 2024
1 parent 54b5f2b commit e2e9936
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 8 deletions.
26 changes: 18 additions & 8 deletions lib/json/common.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,16 @@ class << self
# ruby = [0, 1, nil]
# JSON[ruby] # => '[0,1,null]'
def [](object, opts = {})
if object.respond_to? :to_str
JSON.parse(object.to_str, opts)
else
JSON.generate(object, opts)
if object.is_a?(String)
return JSON.parse(object, opts)
elsif object.respond_to?(:to_str)
str = object.to_str
if str.is_a?(String)
return JSON.parse(object.to_str, opts)
end
end

JSON.generate(object, opts)
end

# Returns the JSON parser class that is used by JSON. This is either
Expand Down Expand Up @@ -693,11 +698,16 @@ def jj(*objs)
# The _opts_ argument is passed through to generate/parse respectively. See
# generate and parse for their documentation.
def JSON(object, *args)
if object.respond_to? :to_str
JSON.parse(object.to_str, args.first)
else
JSON.generate(object, args.first)
if object.is_a?(String)
return JSON.parse(object, args.first)
elsif object.respond_to?(:to_str)
str = object.to_str
if str.is_a?(String)
return JSON.parse(object.to_str, args.first)
end
end

JSON.generate(object, args.first)
end
end

Expand Down
22 changes: 22 additions & 0 deletions test/json/json_common_interface_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@
class JSONCommonInterfaceTest < Test::Unit::TestCase
include JSON

module MethodMissing
def method_missing(name, *args); end
def respond_to_missing?(name, include_private)
true
end
end

def setup
@hash = {
'a' => 2,
Expand All @@ -17,12 +24,26 @@ def setup
'h' => 1000.0,
'i' => 0.001
}

@hash_with_method_missing = {
'a' => 2,
'b' => 3.141,
'c' => 'c',
'd' => [ 1, "b", 3.14 ],
'e' => { 'foo' => 'bar' },
'g' => "\"\0\037",
'h' => 1000.0,
'i' => 0.001
}
@hash_with_method_missing.extend MethodMissing

@json = '{"a":2,"b":3.141,"c":"c","d":[1,"b",3.14],"e":{"foo":"bar"},'\
'"g":"\\"\\u0000\\u001f","h":1000.0,"i":0.001}'
end

def test_index
assert_equal @json, JSON[@hash]
assert_equal @json, JSON[@hash_with_method_missing]
assert_equal @hash, JSON[@json]
end

Expand Down Expand Up @@ -129,6 +150,7 @@ def test_dump_should_modify_defaults

def test_JSON
assert_equal @json, JSON(@hash)
assert_equal @json, JSON(@hash_with_method_missing)
assert_equal @hash, JSON(@json)
end

Expand Down

0 comments on commit e2e9936

Please sign in to comment.