在Ruby中,有沒有辦法在嘗試解析它之前檢查一個字符串是否是有效的json?在試圖解析它之前檢查一個字符串是否有效json?
例如從某些其他網址獲取一些信息,有時會返回json,有時會返回不是有效響應的垃圾。
我的代碼:
def get_parsed_response(response)
parsed_response = JSON.parse(response)
end
在Ruby中,有沒有辦法在嘗試解析它之前檢查一個字符串是否是有效的json?在試圖解析它之前檢查一個字符串是否有效json?
例如從某些其他網址獲取一些信息,有時會返回json,有時會返回不是有效響應的垃圾。
我的代碼:
def get_parsed_response(response)
parsed_response = JSON.parse(response)
end
您可以分析這種方式
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
請注意,如果在
您可以創建一個方法做檢查:
def valid_json?(json)
JSON.parse(json)
return true
rescue JSON::ParserError => e
return false
end
營救異常是危險的。只有在絕對必要時才能使用它。而不是救一些例外,如下所示: rescue TypeError,JSON :: ParserError等 – Houen 2015-12-01 16:08:20
Hey Thanx Houen。更新代碼 – 2015-12-02 09:57:54
不需要使用「開始」。 def - rescue - end應該可以工作 – 2017-04-03 10:20:58
我覺得parse_json
應該返回nil
如果它是無效的並且不應該出錯。
def parse_json string
JSON.parse(string) rescue nil
end
unless json = parse_json string
parse_a_different_way
end
因爲它更漂亮...實際上,我正在考慮打開JSON並創建一個名爲parse_without_error的方法。 – stevo999999 2017-03-13 21:18:16
請注意'null'和'false'也是有效的JSON。 'JSON.parse'返回'nil'和'false',在上面的代碼中將被視爲解析錯誤。 – 2017-10-03 10:35:43
我很肯定地解析它是唯一可以肯定它是有效的方法。爲什麼不解析它並處理解析錯誤,告訴你它是無效的?例如 – 2014-10-07 09:35:39
這種方式'JSON.parse(string)rescue nil' – gotva 2014-10-07 09:36:30
理論上應該有一種方法。解析一個字符串會導致比知道它是否可解析的信息更強的信息。在喬姆斯基的術語中,關於自然語言,這種區分對應於強生成能力和弱生成能力。但是,與上述註釋一樣,恢復錯誤有什麼問題? – sawa 2014-10-07 09:53:26