在尝试解析字符串之前检查字符串是否是有效的 json?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26232909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if a string is valid json before trying to parse it?
提问by Sam
In Ruby, is there a way to check if a string is valid json before trying to parse it?
在 Ruby 中,有没有办法在尝试解析字符串之前检查字符串是否是有效的 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.
例如,从其他一些 url 获取一些信息,有时它返回 json,有时它可能返回一个垃圾,这不是一个有效的响应。
My code:
我的代码:
def get_parsed_response(response)
parsed_response = JSON.parse(response)
end
回答by Richa Sinha
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
回答by gotva
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
回答by stevo999999
I think parse_jsonshould return nilif it's invalid and shouldn't error out.
我认为parse_json应该返回nil如果它无效并且不应该出错。
def parse_json string
JSON.parse(string) rescue nil
end
unless json = parse_json string
parse_a_different_way
end

