3

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) 
2
  • 1
    The link shows a definition for a function which you'd call as valid_json?(response), if you put it into your code. Also, since you'll invariably try to parse the JSON after ascertaining that it is valid, you'd just be doing the same thing twice. Just parse your JSON and rescue from an error, forget about valid_json?. Commented Nov 17, 2014 at 5:40
  • Why not leverage the power of unless instead of old if not? Commented Nov 18, 2014 at 5:08

2 Answers 2

3

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 
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.