gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:11:30 29 4
gpt4 key购买 nike

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

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com