26

How do I avoid parsing JSON if the response body will not be in JSON, else it throws a huge exception which I would like to handle

      def execute_method(foo)
...

        response = self.class.get("/foo.php", query: query)
        JSON.parse(response.body)
      end
1
  • 1
    I don't want to parse, I would like to find out before parsing. How should I do that? Commented Jan 16, 2015 at 12:05

1 Answer 1

59

As @Anthony pointed out, use begin/rescue.

begin
  ...
  JSON.parse(response.body)
rescue JSON::ParserError
  # Handle error
end

Update

To check if a string is a valid json, you can create a method:

def valid_json?(string)
  !!JSON.parse(string)
rescue JSON::ParserError
  false
end

valid_json?("abc") #=> false
valid_json?("{}") #=> true
Sign up to request clarification or add additional context in comments.

2 Comments

I don't want to parse, I would like to find out before parsing. How should I do that?
@Rpj I added a method to check if string is a valid json. I don't think there is any other way to be absolutely sure, other than trying to successfully parse it.

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.