Checking if a string is valid json before trying to parse it?
In Ruby, is there a way to check if a string is valid json before trying to parse it?
For example getting some information from some other urls, sometimes it returns json, sometimes it could return a garbage which is not a valid response.
My code:
def get_parsed_response(response)
parsed_response = JSON.parse(response)
end
You can create a method to do the checking:
def valid_json?(json)
JSON.parse(json)
return true
rescue JSON::ParserError => e
return false
end
You can parse it this way
begin
JSON.parse(string)
rescue JSON::ParserError => e
# do smth
end
# or for method get_parsed_response
def get_parsed_response(response)
parsed_response = JSON.parse(response)
rescue JSON::ParserError => e
# do smth
end