Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

valid_json? check in ruby is not working

Tags:

json

ruby

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)
like image 997
Sam Avatar asked Nov 19 '25 03:11

Sam


2 Answers

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
like image 142
Amadan Avatar answered Nov 20 '25 18:11

Amadan


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.

like image 33
user513951 Avatar answered Nov 20 '25 17:11

user513951



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!