ruby-on-rails - rails : Pretty print JSON without overkill

标签 ruby-on-rails ruby-on-rails-4

我正在使用以下代码在 JSON 中显示未经授权的消息:

def render_unauthorized
  # Displays the Unauthorized message since the user did
  # not pass proper authentication parameters.
  self.headers['WWW-Authenticate'] = 'Token realm="API"'
  render json: { 
    error: { 
      type: "unauthorized",
      message: "This page cannot be accessed without a valid API key." 
      } 
    }, status: 401
end

哪些输出:

{"error":{"type":"unauthorized","message":"This page cannot be accessed without a valid API key."}}



所以我的问题是:有没有办法漂亮地打印这条消息 (无需将其放在单独的 View 中并使用一些 3rd 方 gem )。

编辑:什么是 pretty-print ?

适当间隔,以及..漂亮。这是我想看到的输出:
{
  "error": {
    "type": "unauthorized",
    "message": "This page cannot be accessed without a valid API key." 
  }
}

解决方案

使用@emaillenin 下面的回答有效。为了记录,这里是最终代码的样子(因为他没有包括整个事情):
def render_unauthorized
  # Displays the Unauthorized message since the user did
  # not pass proper authentication parameters.
  self.headers['WWW-Authenticate'] = 'Token realm="API"'
  render json: JSON.pretty_generate({ # <-- Here it is :')
    error: { 
      type: "unauthorized",
      message: "This page cannot be accessed without a valid API key." 
      } 
    }), status: 401
end

最佳答案

使用 JSON 中内置的这个辅助方法。

JSON.pretty_generate

我刚试过,它有效:
> str = '{"error":{"type":"unauthorized","message":"This page cannot be accessed without a valid API key."}}'
> JSON.pretty_generate(JSON.parse(str))
 => "{\n  \"error\": {\n    \"type\": \"unauthorized\",\n    \"message\": \"This page cannot be accessed without a valid API key.\"\n  }\n}"

关于ruby-on-rails - rails : Pretty print JSON without overkill,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24983125/

相关文章:

sql - 如何在Rails中组合内连接和左外连接

ruby-on-rails - 尝试获取哈希值时的 `try` 方法

ruby-on-rails - Heroku Rails Angular JS 编译 Assets

ruby-on-rails - 将元数据添加到使用 Wicked PDF 生成的 PDF

ruby-on-rails - 使用|| Rails中的Case开关

ruby-on-rails - 缺少模板 rails

ruby-on-rails - Rails 中 RESTful 路由的更新操作(PATCH 或 PUT)

ruby-on-rails - 如何在 OpsWorks 部署到 Rails 堆栈期间始终运行迁移

ruby-on-rails-4 - rails 4 部署 - rake stderr : config.eager_load 设置为 nil .. 不正确的错误消息

ruby-on-rails - 命令轨服务器