0

I am working with an API that is returning a "JSON string"...which means that it's returning text wrapped with double quotes:

response = HTTParty.get('http://api.example.com')
response.body == '"token"'

For all of my requests, I am abstracting the API request and automatically using JSON.parse(response.body), but in this case, it chokes on the string because it's not a JSON object.

I guess I can add an extra logic branch to check if it's a string, don't parse as JSON. How should I extract the string out of this string?

1
  • 1
    response.body[1..-2]? Commented Jun 14, 2014 at 5:30

3 Answers 3

1

Use regex

s = '"token"'
str = s[/\A"(.+)"\Z/, 1]
puts str # => token
Sign up to request clarification or add additional context in comments.

Comments

1

Try:

JSON.parse(response.body) rescue response.body[1..-2]

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.