在尝试解析字符串之前检查字符串是否为有效的json? [英] Checking if a string is valid json before trying to parse it?
本文介绍了在尝试解析字符串之前检查字符串是否为有效的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
这篇关于在尝试解析字符串之前检查字符串是否为有效的json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文