我希望我在Ruby on Rails中的JSON输出“漂亮”或格式化得很好。
现在,我调用to_json,我的JSON都在一行上。有时,很难看出JSON输出流中是否有问题。
有办法配置,使我的JSON“漂亮”或很好的格式在Rails?
我希望我在Ruby on Rails中的JSON输出“漂亮”或格式化得很好。
现在,我调用to_json,我的JSON都在一行上。有时,很难看出JSON输出流中是否有问题。
有办法配置,使我的JSON“漂亮”或很好的格式在Rails?
当前回答
我使用了宝石CodeRay,它工作得很好。格式包括颜色,它可以识别很多不同的格式。
我已经在一个可以用来调试rails api的gem上使用了它,它工作得非常好。
顺便说一下,这个gem被命名为'api_explorer' (http://www.github.com/toptierlabs/api_explorer)
其他回答
多亏了机架中间件和Rails 3,你可以为每个请求输出漂亮的JSON,而无需更改应用程序的任何控制器。我已经编写了这样的中间件片段,我在浏览器和curl输出中得到了漂亮的打印JSON。
class PrettyJsonResponse
def initialize(app)
@app = app
end
def call(env)
status, headers, response = @app.call(env)
if headers["Content-Type"] =~ /^application\/json/
obj = JSON.parse(response.body)
pretty_str = JSON.pretty_unparse(obj)
response = [pretty_str]
headers["Content-Length"] = pretty_str.bytesize.to_s
end
[status, headers, response]
end
end
上面的代码应该放在app/middleware/pretty_json_response中。您的Rails项目的rb。 最后一步是在config/environments/development.rb中注册中间件:
config.middleware.use PrettyJsonResponse
我不建议在生产中使用它。JSON的重新解析可能会降低你的产品应用的响应时间和吞吐量。最终,额外的逻辑,如'X-Pretty-Json: true'头可能会被引入,以触发手动curl请求按需格式化。
(在Rails 3.2.8-5.0.0, Ruby 1.9.3-2.2.0, Linux下测试)
看看Awesome Print吧。将JSON字符串解析为Ruby Hash,然后用ap显示它,如下所示:
require "awesome_print"
require "json"
json = '{"holy": ["nested", "json"], "batman!": {"a": 1, "b": 2}}'
ap(JSON.parse(json))
通过以上,你会看到:
{
"holy" => [
[0] "nested",
[1] "json"
],
"batman!" => {
"a" => 1,
"b" => 2
}
}
Awesome Print还会添加一些Stack Overflow无法显示的颜色。
如果你想:
自动美化应用程序中所有传出的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
# 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
漂亮的打印变体(Rails):
my_obj = {
'array' => [1, 2, 3, { "sample" => "hash"}, 44455, 677778, nil ],
foo: "bar", rrr: {"pid": 63, "state with nil and \"nil\"": false},
wwww: 'w' * 74
}
require 'pp'
puts my_obj.as_json.pretty_inspect.
gsub('=>', ': ').
gsub(/"(?:[^"\\]|\\.)*"|\bnil\b/) {|m| m == 'nil' ? 'null' : m }.
gsub(/\s+$/, "")
结果:
{"array": [1, 2, 3, {"sample": "hash"}, 44455, 677778, null],
"foo": "bar",
"rrr": {"pid": 63, "state with nil and \"nil\"": false},
"wwww":
"wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww"}