在尝试解析字符串之前检查字符串是否有效json?

Sam*_*Sam 50 ruby json

在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)

  • 救援异常是危险的.它应该只在绝对必要时使用.而是拯救几个异常,如下所示:rescue TypeError,JSON :: ParserError等. (8认同)
  • 您也不需要“返回”。 (4认同)
  • 不需要使用"开始".def - rescue - end应该有效 (3认同)

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)

  • 请注意,如果<string>下有一些无法隐式转换为字符串的内容(例如nil),则可能会出现“TypeError” (2认同)

ste*_*999 7

我认为如果无效,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)

  • 因为它更漂亮……事实上,我正在考虑开放 JSON 并创建一个名为 parse_without_error 的方法。 (2认同)