代码之家  ›  专栏  ›  技术社区  ›  JP Richardson

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

  •  556
  • JP Richardson  · 技术社区  · 16 年前

    我希望RubyonRails中的JSON输出是“漂亮的”或格式良好的。

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

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

    16 回复  |  直到 16 年前
        1
  •  889
  •   Jason Martin    8 年前

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

    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"
    }
    
        2
  •  68
  •   gertas    8 年前

    由于使用了机架中间件和Rails3,您可以为每个请求输出漂亮的JSON,而无需更改应用程序的任何控制器。我已经编写了这样的中间件片段,并且在浏览器和 curl 输出。

    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
    

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

    config.middleware.use PrettyJsonResponse
    

    我不建议在 production.rb .JSON修复可能会降低生产应用程序的响应时间和吞吐量。最终,可能会引入额外的逻辑,例如“x-pretty-json:true”头,以根据需要触发手动curl请求的格式化。

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

        3
  •  63
  •   the Tin Man    11 年前

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

    <% if !@data.blank? %>
       <pre><%= JSON.pretty_generate(@data) %></pre>
    <% end %>
    
        4
  •  20
  •   Ed Lebert    11 年前

    如果你想:

    1. 自动美化应用程序中所有传出的JSON响应。
    2. 避免污染目标
    3. 避免使用中间件解析/重新呈现JSON(糟糕!)
    4. 沿着铁轨走!

    那么……替换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
    
        5
  •  11
  •   Nhan Jonesinator    8 年前

    退房 awesome_print . 将JSON字符串解析为Ruby散列,然后以类似这样的出色打印方式显示:

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

        6
  •  10
  •   Thomas Klemm    11 年前

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

    pp User.first.as_json
    
    # => {
     "id" => 1,
     "first_name" => "Polar",
     "last_name" => "Bear"
    }
    
        7
  •  10
  •   Phrogz    10 年前

    如果你(像我一样)发现 pretty_generate Ruby的JSON库中内置的选项不够“漂亮”,我推荐自己的选项。 NeatJSON 宝石的格式。

    使用它 gem install neatjson 然后使用 JSON.neat_generate 而不是 JSON.pretty_generate .

    像露比一样 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 进一步自定义输出。例如,冒号前后有多少空格?在逗号之前/之后?在数组和对象的括号内?是否要对对象的键进行排序?你想让上校们排成一排吗?

        8
  •  10
  •   oj5th    8 年前

    使用 <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>
    
        9
  •  6
  •   Community CDub    8 年前

    这是一个中间件解决方案,修改自 this excellent answer by @gertas . 这个解决方案不是特定于Rails的——它应该与任何机架应用程序一起工作。

    这里使用的中间件技术,每个都使用 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在其版本的解决方案中警告的那样,避免在生产中使用它。有点慢。

    用轨道4.1.6测试。

        10
  •  5
  •   Буянбат Чойжилсүрэн    8 年前
    #At Controller
    def branch
        @data = Model.all
        render json: JSON.pretty_generate(@data.as_json)
    end
    
        11
  •  2
  •   Christopher Mullins    12 年前

    这是我自己搜索时从其他帖子中得到的解决方案。

    这允许您根据需要将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
    
        12
  •  2
  •   Tony    11 年前

    我用过gem coderay,它工作得很好。格式包括颜色,它识别出许多不同的格式。

    我在一个gem上使用了它,这个gem可以用于调试RailsAPI,并且工作得很好。

    顺便说一下,这个宝石叫做“api_explorer”( http://www.github.com/toptierlabs/api_explorer )

        13
  •  2
  •   sealocal    9 年前

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

    def index
      my_json = '{ "key": "value" }'
      render json: JSON.pretty_generate( JSON.parse my_json )
    end
    
        14
  •  1
  •   TheDadman    11 年前

    我使用下面的内容,因为我发现头、状态和JSON输出非常有用 一套。根据铁路运输公司的建议,在以下地点制定了呼叫程序: http://railscasts.com/episodes/151-rack-middleware?autoplay=true

      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
  •   Jim Flood    9 年前

    如果您正在使用 RABL 您可以按照说明进行配置 here 要使用json.pretty生成:

    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
    
        16
  •  1
  •   Sergio Belevskij    9 年前
    
    # 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