在 Ruby 中,有没有办法在尝试解析字符串之前检查它是否是有效的 json?
例如从其他一些 url 获取一些信息,有时它返回 json,有时它可能返回一个无效响应的垃圾。
我的代码:
def get_parsed_response(response)
parsed_response = JSON.parse(response)
end
最佳答案
您可以创建一个方法来进行检查:
def valid_json?(json)
JSON.parse(json)
true
rescue JSON::ParserError, TypeError => e
false
end
关于ruby - 在尝试解析之前检查字符串是否是有效的 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26232909/