在Ruby中,有没有办法在尝试解析之前检查字符串是否有效json?
例如,从其他一些网址获取一些信息,有时会返回json,有时它会返回一个垃圾而不是有效的响应.
我的代码:
def get_parsed_response(response)
parsed_response = JSON.parse(response)
end
Run Code Online (Sandbox Code Playgroud)
Ric*_*nha 62
您可以创建一个方法来进行检查:
def valid_json?(json)
JSON.parse(json)
return true
rescue JSON::ParserError => e
return false
end
Run Code Online (Sandbox Code Playgroud)
got*_*tva 21
你可以用这种方式解析它
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
Run Code Online (Sandbox Code Playgroud)
我认为如果无效,parse_json
应该返回nil
,并且不应出错。
def parse_json string
JSON.parse(string) rescue nil
end
unless json = parse_json string
parse_a_different_way
end
Run Code Online (Sandbox Code Playgroud)