在尝试解析字符串之前检查字符串是否为有效的json?

问题描述:

在Ruby中,有没有办法在尝试解析字符串之前检查字符串是否为有效的json?

In Ruby, is there a way to check if a string is valid json before trying to parse it?

例如,从其他网址获取一些信息,有时返回json,有时可能返回无效响应的垃圾.

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.

我的代码:

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