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
The best way to catch invalid JSON parsing errors is to put the calls to JSON. parse() to a try/catch block.
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.
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.
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
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