Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle JSON parser errors in ruby

Tags:

json

ruby

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
like image 978
Rpj Avatar asked Jan 14 '15 13:01

Rpj


People also ask

How do you handle JSON parsing errors?

The best way to catch invalid JSON parsing errors is to put the calls to JSON. parse() to a try/catch block.

What does JSON parse Do Ruby?

Once we have the file loaded, we can parse the JSON data using the JSON. parse method. This method will create a Ruby hash with the JSON keys. Once loaded, we can proceed to work with the data like an ordinary Ruby hash.

What is JSON parser error?

The "SyntaxError: JSON. parse: unexpected character" error occurs when passing a value that is not a valid JSON string to the JSON. parse method, e.g. a native JavaScript object. To solve the error, make sure to only pass valid JSON strings to the JSON.


1 Answers

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
like image 177
Magnuss Avatar answered Sep 20 '22 17:09

Magnuss