如何在 rails 中打印可以是 JSON 或非 JSON 的 api 响应?

How to print an api response which can be either JSON or non-JSON in rails?

我有一个方法可以输出 api 响应。响应可以是 JSON 响应或非 JSON 响应。对于JSON响应,我的代码如下:


def process
  if success?
    JSON.parse(response.body)
  else
    handle_failure
  end
end

对于非 JSON 响应,我将 'eval' 用作:


def process
  if success?
    eval(response.body)
  else
    handle_failure
  end
end

但是由于响应可以是任何内容,我如何确保它在两种情况下都打印出响应?

谢谢

使用Checking if a string is valid json before trying to parse it?中的方法,定义一个方法来检查正文是否是JSON:

def valid_json?(json)
  JSON.parse(json)
  return true
rescue JSON::ParserError => e
  return false
end

在上面的 class 中,您可以执行以下操作:

def process
  valid_json?(response.body) ? process_json : process_non_json
end

def valid_json?(json)
  JSON.parse(json)
  return true
rescue JSON::ParserError => e
  return false
end

def process_json
  if success?
    JSON.parse(response.body)
  else
    handle_failure
  end
end

def process_non_json
  if success?
    eval(response.body)
  else
    handle_failure
  end
end