Why not sniff for the normal JSON open/close characters [...] and {...} used to define objects?
Here's how objects look converted to JSON:
require 'json'
puts JSON[{'foo' => 1}]
puts JSON[[1, 2]]
# >> {"foo":1}
# >> [1,2]
Checking to make sure those are valid string representations:
JSON['{"foo":1}'] # => {"foo"=>1}
JSON['[1,2]'] # => [1, 2]
Here's how I'd write some code to sniff whether the string passed in looks like a valid JSON string, or just a string with wrapping double-quotes:
require 'json'
def get_object(str)
if str[/^[{\[].+[}\]]$/]
JSON[str]
else
str[1..-2]
end
end
get_object('{"foo":1}') # => {"foo"=>1}
get_object('{"foo":1}').class # => Hash
get_object('[1,2]') # => [1, 2]
get_object('[1,2]').class # => Array
get_object("'bar'") # => "bar"
Notice that on the last line the string 'bar' that's enclosed in single-quotes, is returned as a bare string, i.e., there is no wrapping set of single-quotes so the string is no longer quoted.
It's possible you'd receive a string with white-space leading or following the payload. If so, do something like:
def get_object(str)
if str.strip[/^[{\[].+[}\]]$/]
JSON[str]
else
str.strip[1..-2]
end
end
get_object(' {"foo":1}') # => {"foo"=>1}
get_object(' [1,2] ') # => [1, 2]
get_object(" 'bar'") # => "bar"
response.body[1..-2]?