Sam
Sam

Reputation: 5260

valid_json? check in ruby is not working

I am trying to check whether the response is valid JSON. I am making HTTParty or Restclient request to some urls and checking whether the responses returned are valid JSON?

I referred the link here. This is not working.

My code:

 require 'json'

 def get_parsed_response(response)
   if not response.is_a? String or not response.valid_json?
     # code 
   end
 end

Error:

/home/user/.rvm/gems/ruby-2.1.0/gems/httparty-0.13.1/lib/httparty/response.rb:66:in `method_missing': undefined method `valid_json?' for #<HTTParty::Response:0x00000002497918> (NoMethodError)

Upvotes: 3

Views: 2390

Answers (2)

user513951
user513951

Reputation: 13690

You should be calling response.body.

response is an HTTParty::Response object. What you really want to be working with is the String object that represents the HTTP response body.

Upvotes: 2

Amadan
Amadan

Reputation: 198436

More specifically than in my comment, I suggest you use something like this:

value = nil
begin
  value = JSON.parse(response)
  # do whatever you do when not error
rescue JSON::ParserError, TypeError => e
  puts "Not a string, or not a valid JSON"
  # do whatever you do when error
end

Upvotes: 3

Related Questions