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

发布于 2024-07-05 16:01:12 字数 172 浏览 8 评论 0 原文

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

现在,我调用 to_json 并且我的 JSON 都在一行上。 有时很难看出 JSON 输出流中是否存在问题。

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

I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted.

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.

Is there way to configure to make my JSON "pretty" or nicely formatted in Rails?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

心意如水 2024-07-12 16:01:12

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

Use the pretty_generate() function, built into later versions of JSON. For example:

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"
}
爱的十字路口 2024-07-12 16:01:12

HTML 中的

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

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

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:

<% if @data.present? %>
   <pre><%= JSON.pretty_generate(@data) %></pre>
<% end %>
骷髅 2024-07-12 16:01:12

查看很棒的打印。 将 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 不会向您显示的颜色。

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

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.

清风无影 2024-07-12 16:01:12

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

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.

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:

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.

(Tested with Rails 3.2.8-5.0.0, Ruby 1.9.3-2.2.0, Linux)

浪漫之都 2024-07-12 16:01:12

如果你想处理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-rails 进行格式化我在rails控制台中的代码而不是awesome_print中的代码太冗长了。

pry-rails 示例:

在此处输入图像描述

它还具有语法突出显示。

if you want to handle active_record object, puts is enough.

for example:

  • without 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\"}"
  • with 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

if you are handle the json data, JSON.pretty_generate is a good alternative

Example:

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

Output:

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

if it's in the ROR project, I always prefer to use gem pry-rails to format my codes in the rails console rather than awesome_print which is too verbose.

Example of pry-rails:

enter image description here

it also has syntax highlight.

盗琴音 2024-07-12 16:01:12

这是一个中间件解决方案,修改自@gertas 的这个优秀答案。 该解决方案不是 Rails 特定的——它应该适用于任何 Rack 应用程序。

此处使用的中间件技术(使用 #each)在 ASCIIcasts 151:机架中间件 中进行了解释艾芬·贝德福德。

此代码位于 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 进行测试。

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.

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

This code goes in 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

To turn it on, add this to config/environments/test.rb and config/environments/development.rb:

config.middleware.use "PrettyJsonResponse"

As @gertas warns in his version of this solution, avoid using it in production. It's somewhat slow.

Tested with Rails 4.1.6.

最好是你 2024-07-12 16:01:12

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

pp User.first.as_json

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

Dumping an ActiveRecord object to JSON (in the Rails console):

pp User.first.as_json

# => {
 "id" => 1,
 "first_name" => "Polar",
 "last_name" => "Bear"
}
好菇凉咱不稀罕他 2024-07-12 16:01:12

如果您发现 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?"}
  ]
}

它还支持各种格式化选项以进一步自定义您的输出。 例如,冒号之前/之后有多少个空格? 逗号之前/之后? 数组和对象的括号内? 您想对对象的键进行排序吗? 您希望冒号全部对齐吗?

If you 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.

To use it:

gem install neatjson

and then use

JSON.neat_generate

instead of

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:

{
  "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?

花想c 2024-07-12 16:01:12

使用

 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>

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

<%
  require 'json'

  hash = JSON[{hey: "test", num: [{one: 1, two: 2, threes: [{three: 3, tthree: 33}]}]}.to_json] 
%>

<pre>
  <%=  JSON.pretty_generate(hash) %>
</pre>
终遇你 2024-07-12 16:01:12

如果您想要:

  1. 自动美化应用程序的所有传出 JSON 响应。
  2. 避免污染 Object#to_json/#as_json
  3. 避免使用中间件解析/重新渲染 JSON(恶心!) 按照
  4. RAILS 方式进行!

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

If you want to:

  1. Prettify all outgoing JSON responses from your app automatically.
  2. Avoid polluting Object#to_json/#as_json
  3. Avoid parsing/re-rendering JSON using middleware (YUCK!)
  4. Do it the RAILS WAY!

Then ... replace the ActionController::Renderer for JSON! Just add the following code to your 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
蛮可爱 2024-07-12 16:01: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

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.

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
自此以后,行同陌路 2024-07-12 16:01:12

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

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

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

def index
  my_json = '{ "key": "value" }'
  render json: JSON.pretty_generate( JSON.parse my_json )
end
无尽的现实 2024-07-12 16:01:12
#At Controller
def branch
    @data = Model.all
    render json: JSON.pretty_generate(@data.as_json)
end
#At Controller
def branch
    @data = Model.all
    render json: JSON.pretty_generate(@data.as_json)
end
若水微香 2024-07-12 16:01:12

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

Pretty print variant (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+$/, "")

Result:

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

阳光的暖冬 2024-07-12 16:01:12

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

我已经在可用于调试 Rails API 的 gem 上使用了它,并且效果非常好。

顺便说一句,该 gem 名为“api_explorer”(http://www.github.com/toptierlabs/api_explorer )

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.

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

长伴 2024-07-12 16:01: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

# 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
慕巷 2024-07-12 16:01:12

我使用以下内容,因为我发现标头、状态和 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

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

  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
叫思念不要吵 2024-07-12 16:01:12

我在 Rails 控制台中有一个 JSON 对象,并且想在控制台中很好地显示它(而不是像一个巨大的连接字符串一样显示),它很简单:

data.as_json

I had a JSON object in the rails console, and wanted to display it nicely in the console (as opposed to displaying like a massive concatenated string), it was as simple as:

data.as_json
帥小哥 2024-07-12 16:01:12

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

If you are using RABL you can configure it as described here to use 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:

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
苦妄 2024-07-12 16:01:12

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

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

Simplest example, I could think of:

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

Rails console example:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文