最简单的方法是让Ruby解析整个响应并使用after_filter
再次吐出。在app/controllers/application_controller.rb
中尝试以下代码。
class ApplicationController < ActionController::Base
after_filter :minify_json
private
def minify_json
response.body = JSON.parse(response.body).to_json if request.format.json?
end
end
如果你决定要美化,而不是精缩的JSON,您可以使用此代码:
class ApplicationController < ActionController::Base
after_filter :beautify_json
private
def beautify_json
response.body = JSON.pretty_generate(JSON.parse(response.body)) if request.format.json?
end
end
或者,你可以允许请求方指定使用参数:
class ApplicationController < ActionController::Base
after_filter :format_json
private
def format_json
if request.format.json?
json = JSON.parse(response.body)
response.body = params[:pretty] ? JSON.pretty_generate(json) : json.to_json
end
end
end