加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails:漂亮的打印JSON而不过分

发布时间:2020-12-16 20:41:06 所属栏目:百科 来源:网络整理
导读:我使用以下代码在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: { er
我使用以下代码在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.”}}

所以我的问题是这样的:有没有办法漂亮打印这个消息(没有把它放在一个单独的视图,并使用一些第三方宝石).

编辑:什么是漂亮的打印?

适当间隔,好..漂亮.以下是我想看到的输出:

{
  "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}"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读