【问题标题】:How to Pretty/Awesome Print Response from Google API如何从 Google API 漂亮/真棒打印响应
【发布时间】:2018-01-04 16:06:15
【问题描述】:

我从对 Gmail API 的成功调用中得到以下响应:

#<Google::Apis::GmailV1::Profile:0x00007f9ad2160210 @email_address="email@example.com", @history_id=15581926, @messages_total=174760, @threads_total=127619>

但是,当我使用 awesome_print 或 pretty print 将其打印到控制台时(两者都使用 User.first 之类的测试输出预期格式),它不会将响应重新格式化为可读格式。

我试过了

ap JSON.parse(response)

我明白了

no implicit conversion of Google::Apis::GmailV1::Profile into String

我确定我不了解 API 响应的格式以及 awesome_print 的预期。有没有一种方法可以解析响应,使其在控制台中更具可读性?

【问题讨论】:

  • 试试ap response.to_h我打错了这个问题是JSON不能把它变成String
  • ap response.to_h 工作!谢谢!!

标签: ruby-on-rails json ruby


【解决方案1】:

Google::Apis::GmailV1::Profile 是一个简单的类,它没有实现任何东西来帮助它进行漂亮的打印(to_h 除外,见下文。)

你可以自己做:

Google::Apis::GmailV1::Profile.prepend(Module.new do
  def pp
    %i|email_address history_id messages_total threads_total|.map do |attr|
      [attr, public_send(attr)]
    end.to_h
  end
end)

并使用response.pp 漂亮地打印它。或者,或者,只需使用它默认提供的内容:response.to_h

【讨论】:

【解决方案2】:

将响应转换为哈希是解决方案。

ap response.to_h

【讨论】:

    猜你喜欢
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 2013-12-03
    • 2016-05-03
    • 1970-01-01
    • 2015-01-22
    相关资源
    最近更新 更多