在尝试parsing之前检查一个string是否有效json?

在Ruby中,是否有一种方法来检查一个string是否是有效的JSON之前试图parsing它?

例如从其他url获取一些信息,有时会返回json,有时会返回一个不是有效响应的垃圾。

我的代码:

def get_parsed_response(response) parsed_response = JSON.parse(response) end 

您可以创build一个方法来执行检查:

 def valid_json?(json) JSON.parse(json) return true rescue JSON::ParserError => e return false end 

你可以这样parsing它

 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 

事实上,parse_json应该返回一个零string,如果它是无效的,不应该出错。

 def parse_json string JSON.parse(string) rescue nil end unless json = parse_json string parse_a_different_way end