我希望我在Ruby on Rails中的JSON输出“漂亮”或格式化得很好。

现在,我调用to_json,我的JSON都在一行上。有时,很难看出JSON输出流中是否有问题。

有办法配置,使我的JSON“漂亮”或很好的格式在Rails?


当前回答

如果你想:

自动美化应用程序中所有传出的JSON响应。 避免污染Object#to_json/#as_json 避免使用中间件解析/重新呈现JSON(讨厌!) 用铁路的方式去做!

然后……为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

其他回答

#At Controller
def branch
    @data = Model.all
    render json: JSON.pretty_generate(@data.as_json)
end

如果您发现Ruby JSON库中内置的pretty_generate选项不够“漂亮”,我推荐您使用自己的NeatJSON gem进行格式化。

使用它:

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?"}
  ]
}

它还支持各种格式选项,以进一步自定义输出。例如,冒号前后有多少个空格?之前/之后逗号?在数组和对象的括号内?要对对象的键进行排序吗?你想让冒号都对齐吗?

我使用了宝石CodeRay,它工作得很好。格式包括颜色,它可以识别很多不同的格式。

我已经在一个可以用来调试rails api的gem上使用了它,它工作得非常好。

顺便说一下,这个gem被命名为'api_explorer' (http://www.github.com/toptierlabs/api_explorer)

将ActiveRecord对象转储为JSON(在Rails控制台中):

pp User.first.as_json

# => {
 "id" => 1,
 "first_name" => "Polar",
 "last_name" => "Bear"
}

# example of use:
a_hash = {user_info: {type: "query_service", e_mail: "my@email.com", 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