提问人:JP Richardson 提问时间:9/18/2008 最后编辑:NakilonJP Richardson 更新时间:10/10/2023 访问量:395561
如何“漂亮”格式化 JSON 输出
How to "pretty" format JSON output
问:
我希望我在 Ruby on Rails 中的 JSON 输出是“漂亮”的或格式良好的。
现在,我打电话,我的 JSON 都在一行。有时,很难看出 JSON 输出流中是否存在问题。to_json
有没有办法在Rails中配置使我的JSON“漂亮”或格式化良好?
答:
使用内置于更高版本的 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"
}
评论
format.json { render :json => @whatever }
format.json { render :json => JSON.pretty_generate(my_json) }
多亏了 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.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 版本测试)
评论
obj = JSON.parse(response.body.first)
Rack::Utils.bytesize(pretty_str).to_s
pretty_str.bytesize.to_s
这是我在自己的搜索过程中从其他帖子中得出的解决方案。
这允许您根据需要将 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
HTML 中的标记与 一起使用,将在视图中呈现 JSON 漂亮。当我杰出的老板向我展示这个时,我非常高兴:<pre>
JSON.pretty_generate
<% if @data.present? %>
<pre><%= JSON.pretty_generate(@data) %></pre>
<% end %>
我使用过 gem CodeRay,它运行良好。该格式包括颜色,并且可以识别许多不同的格式。
我已经在可用于调试 rails API 的 gem 上使用了它,它运行良好。
顺便说一句,这颗宝石被命名为“api_explorer”(http://www.github.com/toptierlabs/api_explorer)
我使用以下内容,因为我发现标头、状态和 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
将 ActiveRecord 对象转储到 JSON(在 Rails 控制台中):
pp User.first.as_json
# => {
"id" => 1,
"first_name" => "Polar",
"last_name" => "Bear"
}
评论
pp
User.first.as_json.pretty_inspect
如果你想:
- 自动美化来自应用的所有传出 JSON 响应。
- 避免污染 Object#to_json/#as_json
- 避免使用中间件解析/重新渲染 JSON(YUCK!
- 以 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
评论
json.respond_to?(:to_h)
:to_hash
这是 @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 进行测试。
如果你发现 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?"}
]
}
它还支持多种格式选项,以进一步自定义您的输出。例如,冒号前/后有多少个空格?逗号前/后?在数组和对象的括号内?是否要对对象的键进行排序?你想让冒号都排成一排吗?
如果您使用的是 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
# 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
如果您希望在 Rails 控制器操作中快速实现此操作以发送 JSON 响应:
def index
my_json = '{ "key": "value" }'
render json: JSON.pretty_generate( JSON.parse my_json )
end
查看 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 不会向您显示的颜色。
评论
使用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>
#At Controller
def branch
@data = Model.all
render json: JSON.pretty_generate(@data.as_json)
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"}
我能想到的最简单的例子:
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
如果你想处理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 console
awesome_print
示例:pry-rails
它还具有语法突出显示功能。
我在 rails 控制台中有一个 JSON 对象,并希望在控制台中很好地显示它(而不是像一个巨大的串联字符串一样显示),它就像以下几点一样简单:
data.as_json
评论
.to_json
.as_json
上一个:如何在 Ruby 中获取随机数
下一个:如何使用 Rails 迁移删除列
评论
y my_json
undefined method 'y' for main:Object
y
在 Rails 控制台中可用。