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

时间:2022-02-19 20:48:07

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_json and 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 or a method to make my JSON "pretty" or nicely formatted in Rails?

是否有办法配置或方法使我的JSON“漂亮”或在Rails中格式良好?

16 个解决方案

#1


828  

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

#2


65  

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 curl output.

感谢机架中间件和Rails 3,您可以为每个请求输出漂亮的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.rb of your Rails project. And the final step is to register the middleware in config/environments/development.rb:

上面的代码应该放在app/中间件/pretty_json_response中。您的Rails项目的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.

我不建议在生产中使用它。JSON解析可能会降低您的产品应用程序的响应时间和吞吐量。最终可能会引入额外的逻辑,如“x - prety - JSON: true”头,以根据需要触发手动curl请求的格式。

(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进行测试)

#3


57  

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:

HTML中的

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

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

#4


19  

If you want to:

如果你想:

  1. Prettify all outgoing JSON responses from your app automatically.
  2. 自动美化所有从应用程序发出的JSON响应。
  3. Avoid polluting Object#to_json/#as_json
  4. # to_json / # as_json避免污染对象
  5. Avoid parsing/re-rendering JSON using middleware (YUCK!)
  6. 避免使用中间件解析/重新呈现JSON(呸!)
  7. Do it the RAILS WAY!
  8. 做它的轨道!

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

然后……替换ActionController:::Renderer for JSON!只需在应用程序控制器中添加以下代码:

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

#5


9  

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

#6


9  

If you (like I) find that the pretty_generate option built into Ruby's JSON library is not "pretty" enough, I recommend my own NeatJSON gem for your formatting.

如果您(像我一样)发现内置在Ruby的JSON库中的pretty_generate选项不够“漂亮”,我建议您使用我自己的tidy JSON gem进行格式化。

To use it gem install neatjson and then use JSON.neat_generate instead of JSON.pretty_generate.

要使用它,请安装clean JSON,然后使用JSON。neat_generate代替JSON.pretty_generate。

Like Ruby's pp it 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 options to 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?

它还支持各种格式选项来进一步定制输出。例如,冒号前后有多少个空格?之前/之后逗号?在数组和对象的括号内?要对对象的键进行排序吗?你要把冒号都排好吗?

#7


9  

Check out awesome_print. Parse the JSON string into a Ruby Hash, then display it with awesome_print like so:

查看awesome_print。将JSON字符串解析为Ruby散列,然后用awesome_print显示它:

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也会添加一些不会显示堆栈溢出的颜色:)

#8


8  

Using <pre> html code and pretty_generate is good trick:

使用

 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>

#9


6  

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特有的——它应该适用于任何机架应用程序。

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

这里使用的中间件技术,使用#each,在Eifion Bedford的asciicast 151: Rack middleware中进行了解释。

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

这段代码在app/中间件/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:

要打开它,请将其添加到配置/环境/测试中。rb和配置/环境/ 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。

#10


2  

Here's my solution which I derived from other posts during my own search.

这是我在自己的搜索中从其他文章中得到的解决方案。

This allows you to send the pp and jj output to a file as needed.

这允许您根据需要将pp和jj输出发送到一个文件。

require "pp"
require "json"

class File
  def pp(*objs)
    objs.each {|obj|
      PP.pp(obj, self)
    }
    objs.size <= 1 ? objs.first : objs
  end
  def jj(*objs)
    objs.each {|obj|
      obj = JSON.parse(obj.to_json)
      self.puts JSON.pretty_generate(obj)
    }
    objs.size <= 1 ? objs.first : objs
  end
end

test_object = { :name => { first: "Christopher", last: "Mullins" }, :grades => [ "English" => "B+", "Algebra" => "A+" ] }

test_json_object = JSON.parse(test_object.to_json)

File.open("log/object_dump.txt", "w") do |file|
  file.pp(test_object)
end

File.open("log/json_dump.txt", "w") do |file|
  file.jj(test_json_object)
end

#11


2  

I have used the gem CodeRay and it works pretty well. The format includes colors and it recognises a lot of different formats.

我用过宝石科德雷,效果很好。格式包括颜色,它识别许多不同的格式。

I have used it on a gem that can be used for debugging rails APIs and it works pretty well.

我在一个可以用于调试rails api的gem中使用了它,它工作得很好。

By the way, the gem is named 'api_explorer' (http://www.github.com/toptierlabs/api_explorer)

顺便说一下,gem被命名为“api_explorer”(http://www.github.com/toptierlabs/api_explorer)。

#12


2  

If you're looking to quickly implement this in a Rails controller action to send a JSON response:

如果您希望在Rails控制器操作中快速实现这一功能,可以发送一个JSON响应:

def index
  my_json = '{ "key": "value" }'
  render json: JSON.pretty_generate( JSON.parse my_json )
end

#13


2  

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

#14


1  

I use the following as I find the headers, status and JSON output useful as a set. The call routine is broken out on recommendation from a railscasts presentation at: http://railscasts.com/episodes/151-rack-middleware?autoplay=true

当我发现报头、状态和JSON输出作为一组有用的时候,我使用以下代码

  class LogJson

  def initialize(app)
    @app = app
  end

  def call(env)
    dup._call(env)
  end

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

  def each(&block)
    if @headers["Content-Type"] =~ /^application\/json/
      obj = JSON.parse(@response.body)
      pretty_str = JSON.pretty_unparse(obj)
      @headers["Content-Length"] = Rack::Utils.bytesize(pretty_str).to_s
      Rails.logger.info ("HTTP Headers:  #{ @headers } ")
      Rails.logger.info ("HTTP Status:  #{ @status } ")
      Rails.logger.info ("JSON Response:  #{ pretty_str} ")
    end

    @response.each(&block)
  end
  end

#15


1  

If you are using RABL you can configure it as described here to use JSON.pretty_generate:

如果您正在使用RABL,您可以按照这里的描述配置它来使用JSON.pretty_generate:

class PrettyJson
  def self.dump(object)
    JSON.pretty_generate(object, {:indent => "  "})
  end
end

Rabl.configure do |config|
  ...
  config.json_engine = PrettyJson if Rails.env.development?
  ...
end

A problem with using JSON.pretty_generate is that JSON schema validators will no longer be happy with your datetime strings. You can fix those in your config/initializers/rabl_config.rb with:

使用JSON有一个问题。pretty_generate是JSON模式验证器将不再满意您的datetime字符串。您可以在配置/初始化器/rabl_config中修复它们。rb:

ActiveSupport::TimeWithZone.class_eval do
  alias_method :orig_to_s, :to_s
  def to_s(format = :default)
    format == :default ? iso8601 : orig_to_s(format)
  end
end

#16


1  


# example of use:
a_hash = {user_info: {type: "query_service", e_mail: "my@email.com", phone: "+79876543322"}, cars_makers: ["bmw", "mitsubishi"], car_models: [bmw: {model: "1er", year_mfc: 2006}, mitsubishi: {model: "pajero", year_mfc: 1997}]}
pretty_html = a_hash.pretty_html

# include this module to your libs:
module MyPrettyPrint
    def pretty_html indent = 0
        result = ""
        if self.class == Hash
            self.each do |key, value|
                result += "#{key}

: #{[Array, Hash].include?(value.class) ? value.pretty_html(indent+1) : value}

" end elsif self.class == Array result = "[#{self.join(', ')}]" end "#{result}" end end class Hash include MyPrettyPrint end class Array include MyPrettyPrint end

#1


828  

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

#2


65  

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 curl output.

感谢机架中间件和Rails 3,您可以为每个请求输出漂亮的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.rb of your Rails project. And the final step is to register the middleware in config/environments/development.rb:

上面的代码应该放在app/中间件/pretty_json_response中。您的Rails项目的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.

我不建议在生产中使用它。JSON解析可能会降低您的产品应用程序的响应时间和吞吐量。最终可能会引入额外的逻辑,如“x - prety - JSON: true”头,以根据需要触发手动curl请求的格式。

(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进行测试)

#3


57  

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:

HTML中的

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

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

#4


19  

If you want to:

如果你想:

  1. Prettify all outgoing JSON responses from your app automatically.
  2. 自动美化所有从应用程序发出的JSON响应。
  3. Avoid polluting Object#to_json/#as_json
  4. # to_json / # as_json避免污染对象
  5. Avoid parsing/re-rendering JSON using middleware (YUCK!)
  6. 避免使用中间件解析/重新呈现JSON(呸!)
  7. Do it the RAILS WAY!
  8. 做它的轨道!

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

然后……替换ActionController:::Renderer for JSON!只需在应用程序控制器中添加以下代码:

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

#5


9  

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

#6


9  

If you (like I) find that the pretty_generate option built into Ruby's JSON library is not "pretty" enough, I recommend my own NeatJSON gem for your formatting.

如果您(像我一样)发现内置在Ruby的JSON库中的pretty_generate选项不够“漂亮”,我建议您使用我自己的tidy JSON gem进行格式化。

To use it gem install neatjson and then use JSON.neat_generate instead of JSON.pretty_generate.

要使用它,请安装clean JSON,然后使用JSON。neat_generate代替JSON.pretty_generate。

Like Ruby's pp it 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 options to 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?

它还支持各种格式选项来进一步定制输出。例如,冒号前后有多少个空格?之前/之后逗号?在数组和对象的括号内?要对对象的键进行排序吗?你要把冒号都排好吗?

#7


9  

Check out awesome_print. Parse the JSON string into a Ruby Hash, then display it with awesome_print like so:

查看awesome_print。将JSON字符串解析为Ruby散列,然后用awesome_print显示它:

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也会添加一些不会显示堆栈溢出的颜色:)

#8


8  

Using <pre> html code and pretty_generate is good trick:

使用

 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>

#9


6  

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特有的——它应该适用于任何机架应用程序。

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

这里使用的中间件技术,使用#each,在Eifion Bedford的asciicast 151: Rack middleware中进行了解释。

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

这段代码在app/中间件/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:

要打开它,请将其添加到配置/环境/测试中。rb和配置/环境/ 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。

#10


2  

Here's my solution which I derived from other posts during my own search.

这是我在自己的搜索中从其他文章中得到的解决方案。

This allows you to send the pp and jj output to a file as needed.

这允许您根据需要将pp和jj输出发送到一个文件。

require "pp"
require "json"

class File
  def pp(*objs)
    objs.each {|obj|
      PP.pp(obj, self)
    }
    objs.size <= 1 ? objs.first : objs
  end
  def jj(*objs)
    objs.each {|obj|
      obj = JSON.parse(obj.to_json)
      self.puts JSON.pretty_generate(obj)
    }
    objs.size <= 1 ? objs.first : objs
  end
end

test_object = { :name => { first: "Christopher", last: "Mullins" }, :grades => [ "English" => "B+", "Algebra" => "A+" ] }

test_json_object = JSON.parse(test_object.to_json)

File.open("log/object_dump.txt", "w") do |file|
  file.pp(test_object)
end

File.open("log/json_dump.txt", "w") do |file|
  file.jj(test_json_object)
end

#11


2  

I have used the gem CodeRay and it works pretty well. The format includes colors and it recognises a lot of different formats.

我用过宝石科德雷,效果很好。格式包括颜色,它识别许多不同的格式。

I have used it on a gem that can be used for debugging rails APIs and it works pretty well.

我在一个可以用于调试rails api的gem中使用了它,它工作得很好。

By the way, the gem is named 'api_explorer' (http://www.github.com/toptierlabs/api_explorer)

顺便说一下,gem被命名为“api_explorer”(http://www.github.com/toptierlabs/api_explorer)。

#12


2  

If you're looking to quickly implement this in a Rails controller action to send a JSON response:

如果您希望在Rails控制器操作中快速实现这一功能,可以发送一个JSON响应:

def index
  my_json = '{ "key": "value" }'
  render json: JSON.pretty_generate( JSON.parse my_json )
end

#13


2  

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

#14


1  

I use the following as I find the headers, status and JSON output useful as a set. The call routine is broken out on recommendation from a railscasts presentation at: http://railscasts.com/episodes/151-rack-middleware?autoplay=true

当我发现报头、状态和JSON输出作为一组有用的时候,我使用以下代码

  class LogJson

  def initialize(app)
    @app = app
  end

  def call(env)
    dup._call(env)
  end

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

  def each(&block)
    if @headers["Content-Type"] =~ /^application\/json/
      obj = JSON.parse(@response.body)
      pretty_str = JSON.pretty_unparse(obj)
      @headers["Content-Length"] = Rack::Utils.bytesize(pretty_str).to_s
      Rails.logger.info ("HTTP Headers:  #{ @headers } ")
      Rails.logger.info ("HTTP Status:  #{ @status } ")
      Rails.logger.info ("JSON Response:  #{ pretty_str} ")
    end

    @response.each(&block)
  end
  end

#15


1  

If you are using RABL you can configure it as described here to use JSON.pretty_generate:

如果您正在使用RABL,您可以按照这里的描述配置它来使用JSON.pretty_generate:

class PrettyJson
  def self.dump(object)
    JSON.pretty_generate(object, {:indent => "  "})
  end
end

Rabl.configure do |config|
  ...
  config.json_engine = PrettyJson if Rails.env.development?
  ...
end

A problem with using JSON.pretty_generate is that JSON schema validators will no longer be happy with your datetime strings. You can fix those in your config/initializers/rabl_config.rb with:

使用JSON有一个问题。pretty_generate是JSON模式验证器将不再满意您的datetime字符串。您可以在配置/初始化器/rabl_config中修复它们。rb:

ActiveSupport::TimeWithZone.class_eval do
  alias_method :orig_to_s, :to_s
  def to_s(format = :default)
    format == :default ? iso8601 : orig_to_s(format)
  end
end

#16


1  


# example of use:
a_hash = {user_info: {type: "query_service", e_mail: "my@email.com", phone: "+79876543322"}, cars_makers: ["bmw", "mitsubishi"], car_models: [bmw: {model: "1er", year_mfc: 2006}, mitsubishi: {model: "pajero", year_mfc: 1997}]}
pretty_html = a_hash.pretty_html

# include this module to your libs:
module MyPrettyPrint
    def pretty_html indent = 0
        result = ""
        if self.class == Hash
            self.each do |key, value|
                result += "#{key}

: #{[Array, Hash].include?(value.class) ? value.pretty_html(indent+1) : value}

" end elsif self.class == Array result = "[#{self.join(', ')}]" end "#{result}" end end class Hash include MyPrettyPrint end class Array include MyPrettyPrint end