2013-02-26 57 views
6

我使用.json.erb視圖而不是調用to_json方法。如何縮小Rails中的JSON輸出?

我發現了幾個關於JSON輸出縮小的建議。有人告訴我們關於壓縮web應用程序的所有輸出,其他人建議使用after filterbefore render,但他們沒有解釋如何在JSON元素之間縮小空格和製表符,以及從哪裏接收JSON輸入以及從哪裏放置縮小的結果。第三條建議嚴格地講述瞭如何縮小JavaScript。

回答

4

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