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)
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With