如何“漂亮”格式化 JSON 输出

How to "pretty" format JSON output

提问人:JP Richardson 提问时间:9/18/2008 最后编辑:NakilonJP Richardson 更新时间:10/10/2023 访问量:395561

问:

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

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

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

ruby-on-rails 红宝石 json 漂亮打印

评论

11赞 the Tin Man 6/9/2011
执行此操作时要记住的一件事是,由于额外的空格,JSON 内容的大小会膨胀。在开发环境中,让 JSON 易于阅读通常很有帮助,但在生产环境中,你希望你的内容尽可能精简,以便在用户的浏览器中提高速度和响应能力。
3赞 Ryan Florence 8/18/2009
不知道你在哪里看它,但在 webkit 的控制台中,它会从记录或请求的任何 JSON 中创建一棵漂亮的树。
2赞 randomor 2/3/2013
如果您想要一些快速修复,请使用可以很好地格式化内容。y my_json
5赞 nurettin 4/11/2013
@randomorundefined method 'y' for main:Object
0赞 Sophia Feng 6/22/2016
y在 Rails 控制台中可用。

答:

1157赞 lambshaanxy 12/1/2009 #1

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

评论

40赞 TheDeadSerious 11/22/2010
漂亮!我已经把它放进了我的~/.irbrc: def json_pp(json) put JSON.pretty_generate(JSON.parse(json)) end
12赞 iconoclast 9/20/2011
为了使这在 Rails 中有用,您似乎应该给出一个答案,其中包括可以在与format.json { render :json => @whatever }
12赞 lambshaanxy 9/20/2011
当然,prettyprinting 应该只用于服务器端调试吗?如果你把上面的代码放在控制器中,你将在所有响应中拥有大量无用的空格,这甚至不是客户端调试所必需的,因为任何工具都值得一试(例如。Firebug) 已经处理了漂亮的打印 JSON。
12赞 iconoclast 9/20/2011
@jpatokal:你可能会考虑还有其他更好的选择,但问题是如何在 Rails 中实现这一点。说“你不想在 Rails 中这样做”是没有答案的。显然,很多人都想用 Rails 来做这件事。
41赞 lambshaanxy 9/21/2011
最初的发帖人没有说他想在 Rails 应用程序中的哪个位置使用它,所以我用一行 Ruby 来回答,它可以在任何地方使用。要使用它在 Rails 控制器中生成 JSON 响应,您已经回答了自己的问题:.format.json { render :json => JSON.pretty_generate(my_json) }
82赞 gertas 10/23/2012 #2

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

上面的代码应该放在你的 Rails 项目中。 最后一步是在 :app/middleware/pretty_json_response.rbconfig/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 版本测试)

评论

2赞 Ammo Goettsch 8/30/2013
您如何绕过ActiveSupport对to_json的重新定义?这使我无法在 ActiveSupport 存在时进行漂亮的打印。
1赞 gertas 9/1/2013
我真的不在乎,to_json、as_json、jbuilder,我最常使用 - 无论如何,中间件都会转换任何 JSON 输出。我尽量避免开课。
1赞 Kimmo Lehto 10/1/2013
我必须更改解析行才能使其工作。obj = JSON.parse(response.body.first)
5赞 elsurudo 1/20/2014
在 Rails 4 中也很好用......谢谢!我更喜欢这个而不是更特定于库的方法(如公认的答案)。由于您无论如何都应该只在开发模式下使用它,因此性能影响并不是什么大问题。
3赞 panteo 7/29/2016
在 Rails 5 中,我不得不改用它,它效果很好!Rack::Utils.bytesize(pretty_str).to_spretty_str.bytesize.to_s
5赞 Christopher Mullins 12/23/2012 #3

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

这允许您根据需要将 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
110赞 Roger Garza 7/4/2013 #4

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

<% if @data.present? %>
   <pre><%= JSON.pretty_generate(@data) %></pre>
<% end %>
5赞 Tony 11/22/2013 #5

我使用过 gem CodeRay,它运行良好。该格式包括颜色,并且可以识别许多不同的格式。

我已经在可用于调试 rails API 的 gem 上使用了它,它运行良好。

顺便说一句,这颗宝石被命名为“api_explorer”(http://www.github.com/toptierlabs/api_explorer)

1赞 TheDadman 4/1/2014 #6

我使用以下内容,因为我发现标头、状态和 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
17赞 Thomas Klemm 4/4/2014 #7

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

pp User.first.as_json

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

评论

3赞 Johnny Wong 12/15/2016
若要从中获取字符串而不是打印到标准输出,请使用 .对我来说效果很好。ppUser.first.as_json.pretty_inspect
26赞 Ed Lebert 4/12/2014 #8

如果你想:

  1. 自动美化来自应用的所有传出 JSON 响应。
  2. 避免污染 Object#to_json/#as_json
  3. 避免使用中间件解析/重新渲染 JSON(YUCK!
  4. 以 RAILS 的方式去做!

然后。。。替换 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

评论

0赞 nornagon 4/17/2015
这很棒,但它实际上会导致日期/时间以不同的方式呈现:gist.github.com/nornagon/9c24b68bd6d3e871add3
1赞 Christopher Oezbek 8/19/2015
这有几个问题:(1) JSON.pretty_generate 需要 或 .(2)pretty_generate可能会被to_json不会的东西窒息。json.respond_to?(:to_h):to_hash
0赞 ConorSheehan1 9/28/2018
@nornagon我没有应用此更改,但我得到了您在 .to_json 和 pretty_generate 之间看到的相同差异。我只在 rails 控制台中看到它,而不是普通的 irb。我认为这可能是一个一般的轨道问题,与这个补丁无关。此外,当您将字符串转换回两种格式的时间时,Time.parse 将返回相同的结果。在日志中搜索时间戳时,这只是一个小小的不便,但如果你无论如何都在贪婪,添加一些 \s+ 并不是什么大问题。
0赞 ConorSheehan1 10/1/2018
@nornagon看起来您看到的问题是 ActiveSupport 对 to_json 的重新定义,正如 Ammo Goettsch 的评论中提到的
9赞 Wayne Conrad 10/22/2014 #9

这是 @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 进行测试。

19赞 Phrogz 4/16/2015 #10

如果你发现 Ruby 的 JSON 库中内置的选项不够“漂亮”,我推荐我自己的 NeatJSON gem 来格式化。pretty_generate

要使用它,请执行以下操作:

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

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

2赞 Jim Flood 9/5/2015 #11

如果您使用的是 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
3赞 Sergio Belevskij 11/30/2015 #12

# example of use:
a_hash = {user_info: {type: "query_service", e_mail: "[email protected]", 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
6赞 sealocal 2/17/2016 #13

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

def index
  my_json = '{ "key": "value" }'
  render json: JSON.pretty_generate( JSON.parse my_json )
end
27赞 Synthead 6/30/2016 #14

查看 Awesome Print。将 JSON 字符串解析为 Ruby Hash,然后显示如下: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 不会向您显示的颜色。

评论

0赞 Alireza mohagheghi 11/10/2022
这个真的很好,使结果更容易阅读。它以不同的颜色显示结果,非常适合活动记录、哈希或数组......
19赞 oj5th 8/3/2016 #15

使用HTML代码是很好的技巧:<pre>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赞 Буянбат Чойжилсүрэн 5/16/2017 #16
#At Controller
def branch
    @data = Model.all
    render json: JSON.pretty_generate(@data.as_json)
end
4赞 SergA 5/23/2019 #17

漂亮的打印变体 (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"}

3赞 Martin Carstens 10/24/2019 #18

我能想到的最简单的例子:

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
5赞 TorvaldsDB 12/1/2021 #19

如果你想处理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\":\"[email protected]\",\"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":"[email protected]","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 consoleawesome_print

示例:pry-rails

在此处输入图像描述

它还具有语法突出显示功能。

0赞 stevec 6/24/2022 #20

我在 rails 控制台中有一个 JSON 对象,并希望在控制台中很好地显示它(而不是像一个巨大的串联字符串一样显示),它就像以下几点一样简单:

data.as_json

评论

0赞 stevec 12/8/2022
6 个月后,我回到了自己的答案(在尝试了所有其他答案之后再次)。我经常犯的错误是使用 而不是 ..to_json.as_json