我使用以下代码在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}"