最簡單的方法是讓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