簡體   English   中英

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

[英]How to "pretty" format JSON output in Ruby on Rails

我希望我在 Ruby on Rails 中的 JSON 輸出“漂亮”或格式正確。

現在,我調用to_json並且我的 JSON 都在一條線上。 有時這很難看出 JSON 輸出流中是否存在問題。

有沒有辦法配置讓我的 JSON “漂亮”或在 Rails 中格式正確?

使用在更高版本的 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"
}

HTML 中的<pre>標記與JSON.pretty_generate一起使用,將在您的視圖中呈現漂亮的 JSON。 當我傑出的老板給我看這個時,我很高興:

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

感謝 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”標頭,以按需觸發手動 curl 請求的格式化。

(使用 Rails 3.2.8-5.0.0、Ruby 1.9.3-2.2.0、Linux 測試)

如果你想:

  1. 自動美化來自您的應用程序的所有傳出 JSON 響應。
  2. 避免污染 Object#to_json/#as_json
  3. 避免使用中間件解析/重新渲染 JSON (YUCK!)
  4. 按照鐵路的方式來做!

然后 ... 將 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

看看真棒打印 將 JSON 字符串解析為 Ruby 哈希,然后用ap顯示它,如下所示:

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 不會顯示的顏色。

如果您發現 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?"}
  ]
}

它還支持各種格式選項,以進一步自定義您的輸出。 例如,冒號前后有多少個空格? 逗號之前/之后? 在數組和對象的括號內? 您想對對象的鍵進行排序嗎? 你想讓冒號都排成一行嗎?

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

將 ActiveRecord 對象轉儲為 JSON(在 Rails 控制台中):

pp User.first.as_json

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

這是一個中間件解決方案,由@gertas 這個出色的答案修改而來。 這個解決方案不是 Rails 特定的——它應該適用於任何 Rack 應用程序。

這里使用的中間件技術,使用#each,在ASCIIcasts 151: Rack Middleware by Eifion Bedford 中進行了解釋。

此代碼位於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 測試。

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

如果您希望在 Rails 控制器操作中快速實現此功能以發送 JSON 響應:

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

這是我在自己的搜索過程中從其他帖子中得出的解決方案。

這允許您根據需要將 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

我使用了 gem CodeRay,它工作得很好。 該格式包括顏色,它可以識別許多不同的格式。

我已經在一個可以用於調試 Rails API 的 gem 上使用它,它工作得很好。

順便說一句,gem 被命名為 'api_explorer' ( http://www.github.com/toptierlabs/api_explorer )


# 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

漂亮的打印變體( Rails ):

my_obj = {
  'array' => [1, 2, 3, { "sample" => "hash"}, 44455, 677778, nil ],
  foo: "bar", rrr: {"pid": 63, "state with nil and \"nil\"": false},
  wwww: 'w' * 74
}
require 'pp'
puts my_obj.as_json.pretty_inspect.
            gsub('=>', ': ').
            gsub(/"(?:[^"\\]|\\.)*"|\bnil\b/) {|m| m == 'nil' ? 'null' : m }.
            gsub(/\s+$/, "")

結果:

{"array": [1, 2, 3, {"sample": "hash"}, 44455, 677778, null],
 "foo": "bar",
 "rrr": {"pid": 63, "state with nil and \"nil\"": false},
 "wwww":
  "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww"}

如果要處理 active_record 對象, puts就足夠了。

例如:

  • 沒有puts
2.6.0 (main):0 > User.first.to_json
  User Load (0.4ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT $1  [["LIMIT", 1]]
=> "{\"id\":1,\"admin\":true,\"email\":\"admin@gmail.com\",\"password_digest\":\"$2a$10$TQy3P7NT8KrdCzliNUsZzuhmo40LGKoth2hwD3OI.kD0lYiIEwB1y\",\"created_at\":\"2021-07-20T08:34:19.350Z\",\"updated_at\":\"2021-07-20T08:34:19.350Z\",\"name\":\"Arden Stark\"}"
  • puts
2.6.0 (main):0 > puts User.first.to_json
  User Load (0.3ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT $1  [["LIMIT", 1]]
{"id":1,"admin":true,"email":"admin@gmail.com","password_digest":"$2a$10$TQy3P7NT8KrdCzliNUsZzuhmo40LGKoth2hwD3OI.kD0lYiIEwB1y","created_at":"2021-07-20T08:34:19.350Z","updated_at":"2021-07-20T08:34:19.350Z","name":"Arden Stark"}
=> nil

如果您要處理 json 數據, JSON.pretty_generate是一個不錯的選擇

例子:

obj = {foo: [:bar, :baz], bat: {bam: 0, bad: 1}}
json = JSON.pretty_generate(obj)
puts json

輸出:

{
  "foo": [
    "bar",
    "baz"
  ],
  "bat": {
    "bam": 0,
    "bad": 1
  }
}

如果它在 ROR 項目中,我總是更喜歡使用 gem pry-railsrails console中格式化我的代碼,而不是太冗長的awesome_print

pry-rails示例:

在此處輸入圖像描述

它也有語法高亮。

如果您使用的是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

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

最簡單的例子,我能想到:

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

Rails 控制台示例:

core dev 1555:0> my_json = '{ "name":"John", "age":30, "car":null }'
=> "{ \"name\":\"John\", \"age\":30, \"car\":null }"
core dev 1556:0> puts JSON.pretty_generate(JSON.parse(my_json))
{
  "name": "John",
  "age": 30,
  "car": null
}
=> nil

我使用以下內容,因為我發現標題、狀態和 JSON 輸出作為一個集合很有用。 調用例程是根據 railscasts 演示文稿中的推薦進行的,網址為: 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

我在 rails 控制台中有一個 JSON 對象,並希望在控制台中很好地顯示它(而不是像顯示大量連接字符串一樣),它很簡單:

data.as_json

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM