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

时间:2008-09-17 19:25:17

标签: ruby-on-rails ruby json pretty-print

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

现在,我调用to_json,我的JSON全部在一行上。有时,如果JSON输出流中存在问题,则很难看到。

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

18 个答案:

答案 0 :(得分:911)

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

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

哪个可以帮到你:

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

答案 1 :(得分:69)

感谢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

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

config.middleware.use PrettyJsonResponse

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

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

答案 2 :(得分:65)

HTML中的<pre>标记与JSON.pretty_generate一起使用,会在您的视图中呈现JSON。当我的杰出老板告诉我这件事时,我很高兴:

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

答案 3 :(得分:20)

如果你想:

  1. 自动从您的应用中清除所有传出的JSON响应。
  2. 避免污染Object#to_json / #as_json
  3. 避免使用中间件解析/重新呈现JSON(YUCK!)
  4. 以RAILS方式行事!
  5. 然后......替换JSON的ActionController :: Renderer!只需将以下代码添加到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
    

答案 4 :(得分:11)

结帐awesome_print。将JSON字符串解析为Ruby Hash,然后使用awesome_print显示它,如下所示:

require "awesome_print"
require "json"

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

ap(JSON.parse(json))

通过以上所述,您将看到:

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

awesome_print还会添加一些Stack Overflow不会告诉你的颜色:)

答案 5 :(得分:10)

如果你(像我一样)发现Ruby的JSON库中内置的pretty_generate选项不够“漂亮”,我推荐自己的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以进一步自定义您的输出。例如,冒号之前/之后有多少个空格?逗号之前/之后?在数组和对象的括号内?你想对对象的键进行排序吗?你想要将冒号排成一行吗?

答案 6 :(得分:10)

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

答案 7 :(得分:10)

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

pp User.first.as_json

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

答案 8 :(得分:6)

这是从this excellent answer by @gertas修改的中间件解决方案。此解决方案不是特定于Rails的 - 它应该适用于任何Rack应用程序。

这里使用的中间件技术,使用#each,由Eifion Bedford在ASCIIcasts 151: Rack Middleware解释。

此代码位于 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

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

config.middleware.use "PrettyJsonResponse"

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

使用Rails 4.1.6进行测试。

答案 9 :(得分:5)

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

答案 10 :(得分:2)

如果您希望在Rails控制器操作中快速实现此操作以发送JSON响应:

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

答案 11 :(得分:2)

我使用过宝石CodeRay并且效果非常好。格式包括颜色,它识别许多不同的格式。

我在一个可以用于调试rails API的gem上使用它,它运行得很好。

顺便说一下,宝石名为'api_explorer'(http://www.github.com/toptierlabs/api_explorer

答案 12 :(得分:2)

这是我在自己搜索过程中从其他帖子中获得的解决方案。

这允许您根据需要将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

答案 13 :(得分:1)

我使用以下内容,因为我发现标题,状态和JSON输出有用 一套。根据:http://railscasts.com/episodes/151-rack-middleware?autoplay=true

上的railscasts演示文稿推荐的呼叫例程
  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

答案 14 :(得分:1)

如果您使用RABL,可以按照here所述进行配置,以使用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

使用JSON.pretty_generate的一个问题是JSON模式验证程序将不再满足于您的日期时间字符串。您可以使用以下命令修复config / initializers / 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

答案 15 :(得分: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

答案 16 :(得分:0)

精美印刷版本:

my_object = { :array => [1, 2, 3, { :sample => "hash"}, 44455, 677778, 9900 ], :foo => "bar", rrr: {"pid": 63, "state": false}}
puts my_object.as_json.pretty_inspect.gsub('=>', ': ')

结果:

{"array": [1, 2, 3, {"sample": "hash"}, 44455, 677778, 9900],
 "foo": "bar",
 "rrr": {"pid": 63, "state": false}}

答案 17 :(得分:0)

最简单的例子,我想到:

console.log(
    Object.keys(document.toObject().length)
); // Returns 3

Rails控制台示例:

my_json = '{ "name":"John", "age":30, "car":null }'
puts JSON.pretty_generate(JSON.parse(my_json))