Rails:漂亮的打印JSON没有过度杀伤力

时间:2014-07-27 16:43:12

标签: 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”:“如果没有有效的API密钥,则无法访问此页面。”}}

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

编辑:什么是漂亮的印刷品?

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

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

2 个答案:

答案 0 :(得分:26)

使用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}"

答案 1 :(得分:9)

如果你(像我一样)发现Ruby的JSON库中内置的pretty_generate选项不是&#34;漂亮的&#34;足够的,我推荐自己的NeatJSON gem用于格式化。

要使用gem install neatjson,然后使用JSON.neat_generate代替JSON.pretty_generate

与Ruby的pp一样,它会在适合的时候将对象和数组放在一行上,但根据需要包装到多个。例如:

{
  "navigation.createroute.poi":[
    {"text":"Lay in a course to the Hilton","params":{"poi":"Hilton"}},
    {"text":"Take me to the airport","params":{"poi":"airport"}},
    {"text":"Let's go to IHOP","params":{"poi":"IHOP"}},
    {"text":"Show me how to get to The Med","params":{"poi":"The Med"}},
    {"text":"Create a route to Arby's","params":{"poi":"Arby's"}},
    {
      "text":"Go to the Hilton by the Airport",
      "params":{"poi":"Hilton","location":"Airport"}
    },
    {
      "text":"Take me to the Fry's in Fresno",
      "params":{"poi":"Fry's","location":"Fresno"}
    }
  ],
  "navigation.eta":[
    {"text":"When will we get there?"},
    {"text":"When will I arrive?"},
    {"text":"What time will I get to the destination?"},
    {"text":"What time will I reach the destination?"},
    {"text":"What time will it be when I arrive?"}
  ]
}

它还支持各种formatting options以进一步自定义您的输出。例如,冒号之前/之后有多少个空格?逗号之前/之后?在数组和对象的括号内?你想对对象的键进行排序吗?你想要将冒号排成一行吗?

使用aligned选项可以使输出看起来像这样:

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