如何在 Ruby on Rails 中“漂亮”格式化 JSON 输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/86653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:39:42  来源:igfitidea点击:

How to "pretty" format JSON output in Ruby on Rails

ruby-on-railsrubyjsonpretty-print

提问by JP Richardson

I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted.

我希望 Ruby on Rails 中的 JSON 输出“漂亮”或格式良好。

Right now, I call to_jsonand my JSON is all on one line. At times this can be difficult to see if there is a problem in the JSON output stream.

现在,我打电话to_json,我的 JSON 都在一条线上。有时很难看出 JSON 输出流中是否存在问题。

Is there way to configure to make my JSON "pretty" or nicely formatted in Rails?

有没有办法配置使我的 JSON “漂亮”或在 Rails 中格式化得很好?

回答by lambshaanxy

Use the pretty_generate()function, built into later versions of JSON. For example:

使用pretty_generate()内置于更高版本 JSON 中的函数。例如:

require 'json'
my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_object)

Which gets you:

这让你:

{
  "array": [
    1,
    2,
    3,
    {
      "sample": "hash"
    }
  ],
  "foo": "bar"
}

回答by gertas

Thanks to Rack Middleware and Rails 3 you can output pretty JSON for every request without changing any controller of your app. I have written such middleware snippet and I get nicely printed JSON in browser and curloutput.

感谢 Rack Middleware 和 Rails 3,您可以为每个请求输出漂亮的 JSON,而无需更改应用程序的任何控制器。我已经编写了这样的中间件片段,并且在浏览器和curl输出中得到了很好的打印 JSON 。

class PrettyJsonResponse
  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, response = @app.call(env)
    if headers["Content-Type"] =~ /^application\/json/
      obj = JSON.parse(response.body)
      pretty_str = JSON.pretty_unparse(obj)
      response = [pretty_str]
      headers["Content-Length"] = pretty_str.bytesize.to_s
    end
    [status, headers, response]
  end
end

The above code should be placed in app/middleware/pretty_json_response.rbof your Rails project. And the final step is to register the middleware in config/environments/development.rb:

上面的代码应该放在app/middleware/pretty_json_response.rb你的 Rails 项目中。最后一步是在以下位置注册中间件config/environments/development.rb

config.middleware.use PrettyJsonResponse

I don't recommend to use it in production.rb. The JSON reparsing may degrade response time and throughput of your production app. Eventually extra logic such as 'X-Pretty-Json: true' header may be introduced to trigger formatting for manual curl requests on demand.

我不建议在production.rb. JSON 重新解析可能会降低生产应用程序的响应时间和吞吐量。最终可能会引入额外的逻辑,例如“X-Pretty-Json: true”标头,以根据需要触发手动卷曲请求的格式化。

(Tested with Rails 3.2.8-5.0.0, Ruby 1.9.3-2.2.0, Linux)

(使用 Rails 3.2.8-5.0.0、Ruby 1.9.3-2.2.0、Linux 测试)

回答by Roger Garza

The <pre>tag in HTML, used with JSON.pretty_generate, will render the JSON pretty in your view. I was so happy when my illustrious boss showed me this:

<pre>HTML 中的标签与 一起使用JSON.pretty_generate,将在您的视图中呈现漂亮的 JSON。当我杰出的老板向我展示这个时,我非常高兴:

<% if @data.present? %>
   <pre><%= JSON.pretty_generate(@data) %></pre>
<% end %>

回答by Ed Lebert

If you want to:

如果你想:

  1. Prettify all outgoing JSON responses from your app automatically.
  2. Avoid polluting Object#to_json/#as_json
  3. Avoid parsing/re-rendering JSON using middleware (YUCK!)
  4. Do it the RAILS WAY!
  1. 自动美化来自您的应用程序的所有传出 JSON 响应。
  2. 避免污染 Object#to_json/#as_json
  3. 避免使用中间件解析/重新呈现 JSON(糟糕!)
  4. 按照铁路方式做!

Then ... replace the ActionController::Renderer for JSON! Just add the following code to your ApplicationController:

然后……将 ActionController::Renderer 替换为 JSON!只需将以下代码添加到您的 ApplicationController 中:

ActionController::Renderers.add :json do |json, options|
  unless json.kind_of?(String)
    json = json.as_json(options) if json.respond_to?(:as_json)
    json = JSON.pretty_generate(json, options)
  end

  if options[:callback].present?
    self.content_type ||= Mime::JS
    "#{options[:callback]}(#{json})"
  else
    self.content_type ||= Mime::JSON
    json
  end
end

回答by Synthead

Check out Awesome Print. Parse the JSON string into a Ruby Hash, then display it with aplike so:

看看真棒打印。将 JSON 字符串解析为 Ruby Hash,然后ap像这样显示它:

require "awesome_print"
require "json"

json = '{"holy": ["nested", "json"], "batman!": {"a": 1, "b": 2}}'

ap(JSON.parse(json))

With the above, you'll see:

有了上面的,你会看到:

{
  "holy" => [
    [0] "nested",
    [1] "json"
  ],
  "batman!" => {
    "a" => 1,
    "b" => 2
  }
}

Awesome Print will also add some color that Stack Overflow won't show you.

Awesome Print 还会添加一些 Stack Overflow 不会显示的颜色。

回答by Thomas Klemm

Dumping an ActiveRecord object to JSON (in the Rails console):

将 ActiveRecord 对象转储到 JSON(在 Rails 控制台中):

pp User.first.as_json

# => {
 "id" => 1,
 "first_name" => "Polar",
 "last_name" => "Bear"
}

回答by oj5th

Using <pre>HTML code and pretty_generateis good trick:

使用<pre>HTML 代码pretty_generate是一个很好的技巧:

<%
  require 'json'

  hash = JSON[{hey: "test", num: [{one: 1, two: 2, threes: [{three: 3, tthree: 33}]}]}.to_json] 
%>

<pre>
  <%=  JSON.pretty_generate(hash) %>
</pre>

回答by Phrogz

If you find that the pretty_generateoption built into Ruby's JSON library is not "pretty" enough, I recommend my own NeatJSONgem for your formatting.

如果您发现pretty_generateRuby 的 JSON 库中内置的选项不够“漂亮”,我建议您使用我自己的NeatJSONgem 进行格式化。

To use it:

要使用它:

gem install neatjson

and then use

然后使用

JSON.neat_generate

instead of

代替

JSON.pretty_generate

Like Ruby's ppit will keep objects and arrays on one line when they fit, but wrap to multiple as needed. For example:

像 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?"}
  ]
}

It also supports a variety of formatting optionsto further customize your output. For example, how many spaces before/after colons? Before/after commas? Inside the brackets of arrays and objects? Do you want to sort the keys of your object? Do you want the colons to all be lined up?

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

回答by Wayne Conrad

Here is a middleware solution modified from this excellent answer by @gertas. This solution is not Rails specific--it should work with any Rack application.

这是从@gertas 这个优秀答案修改的中间件解决方案。这个解决方案不是特定于 Rails 的——它应该适用于任何 Rack 应用程序。

The middleware technique used here, using #each, is explained at ASCIIcasts 151: Rack Middlewareby Eifion Bedford.

此处使用的中间件技术使用 #each,在Eifion Bedford 的ASCIIcasts 151:机架中间件中进行了解释。

This code goes in app/middleware/pretty_json_response.rb:

此代码位于app/middleware/pretty_json_response.rb

class PrettyJsonResponse

  def initialize(app)
    @app = app
  end

  def call(env)
    @status, @headers, @response = @app.call(env)
    [@status, @headers, self]
  end

  def each(&block)
    @response.each do |body|
      if @headers["Content-Type"] =~ /^application\/json/
        body = pretty_print(body)
      end
      block.call(body)
    end
  end

  private

  def pretty_print(json)
    obj = JSON.parse(json)  
    JSON.pretty_unparse(obj)
  end

end

To turn it on, add this to config/environments/test.rb and config/environments/development.rb:

要打开它,请将其添加到 config/environments/test.rb 和 config/environments/development.rb:

config.middleware.use "PrettyJsonResponse"

As @gertas warns in his version of this solution, avoid using it in production. It's somewhat slow.

正如@gertas 在他的解决方案版本中所警告的那样,避免在生产中使用它。它有点慢。

Tested with Rails 4.1.6.

使用 Rails 4.1.6 测试。

回答by Буянбат Чойжилс?рэн

#At Controller
def branch
    @data = Model.all
    render json: JSON.pretty_generate(@data.as_json)
end