我希望我在Ruby on Rails中的JSON输出“漂亮”或格式化得很好。
现在,我调用to_json,我的JSON都在一行上。有时,很难看出JSON输出流中是否有问题。
有办法配置,使我的JSON“漂亮”或很好的格式在Rails?
我希望我在Ruby on Rails中的JSON输出“漂亮”或格式化得很好。
现在,我调用to_json,我的JSON都在一行上。有时,很难看出JSON输出流中是否有问题。
有办法配置,使我的JSON“漂亮”或很好的格式在Rails?
当前回答
下面是根据@gertas的回答修改的中间件解决方案。这个解决方案不是Rails特有的——它应该适用于任何Rack应用程序。
这里使用的中间件技术,使用#each,由Eifion Bedford在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中。config/environments/development.rb:
config.middleware.use "PrettyJsonResponse"
正如@gertas在他的解决方案版本中警告的那样,避免在生产中使用它。有点慢。
使用Rails 4.1.6测试。
其他回答
将ActiveRecord对象转储为JSON(在Rails控制台中):
pp User.first.as_json
# => {
"id" => 1,
"first_name" => "Polar",
"last_name" => "Bear"
}
使用<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>
下面是根据@gertas的回答修改的中间件解决方案。这个解决方案不是Rails特有的——它应该适用于任何Rack应用程序。
这里使用的中间件技术,使用#each,由Eifion Bedford在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中。config/environments/development.rb:
config.middleware.use "PrettyJsonResponse"
正如@gertas在他的解决方案版本中警告的那样,避免在生产中使用它。有点慢。
使用Rails 4.1.6测试。
如果你正在使用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模式验证器将不再满意您的datetime字符串。你可以在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
#At Controller
def branch
@data = Model.all
render json: JSON.pretty_generate(@data.as_json)
end