如何访问这种哈希

how to access this kind of hash

我正在使用 RestClient 发出一个 post 请求,我做了它所以我返回了一个错误响应,所以我可以在控制台中打印这些错误消息

我根据 restclient gem 文档尝试了以下操作

begin
  response = RestClient.post base_uri, params.to_json, content_type: 'application/json', accept: 'application/json'
rescue RestClient::ExceptionWithResponse => err
  error = err.response
  p "this is the error response #{error}"
end

当我打印 err.response 时,我得到以下内容

"this is the error response {\"error\":{\"message\":\"An active access token must be used to query information about the current us er.\",\"type\":\"OAuthException\",\"code\":2500,\"fbtrace_id\":\"HTzmJ0CcIfd\"}}"

如何访问上述哈希中的消息以在控制台中显示它?

尝试过

p "this is the error response #{error.message}"

它给了我 "Bad request" - 不知道它从哪里得到的

如果您只是想输出它:

error = JSON.load(err.response)

puts error['error']['message']

你总是可以把它格式化得更好一点:

puts '[Code %d %s] %s' % [
  error['error']['code'],
  error['error']['type'],
  error['error']['message']
]

请注意,在 Rails 进程中使用 puts 不会很好地工作。您可能想改用 Rails.logger.debug

您收到的回复在 JSON 中。您需要先对 JSON 进行解码,然后再与数据进行交互。就个人而言,我喜欢 MultiJson 这个:

begin
  response = RestClient.post base_uri, params.to_json, content_type: 'application/json', accept: 'application/json'
rescue RestClient::ExceptionWithResponse => err
  error = MultiJson.load(err.response)
  p "this is the error response #{error[:message]}"
end