我怎么"漂亮"的格式,我JSON输出红宝石在轨道上?
-
01-07-2019 - |
题
我想我JSON输出红宝石在轨道上是"漂亮的"或很好格式。
现在,我呼 to_json
和我的JSON是所有的在线之一。有时这可能很难看到如果有一个问题,在id输出流。
是有的方式配置或方法使我JSON"漂亮"或很好的格式在轨道?
解决方案
使用 pretty_generate()
功能,建成后版本的手机中。例如:
require 'json'
my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_object)
这让你:
{
"array": [
1,
2,
3,
{
"sample": "hash"
}
],
"foo": "bar"
}
其他提示
感谢架的中间件和轨3你可以输出漂亮的请求每个请求都没有改变任何控制你的程序。我已经写入这样的中间段我得到很好的印JSON在浏览器和 curl
输出。
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.rb
你轨道的项目。和最后一步是登记的中间件 config/environments/development.rb
:
config.middleware.use PrettyJsonResponse
我不建议使用它 production.rb
.Java重新分析将可能会降低反应的时间,吞吐量的生产应用程序。最终额外的逻辑,如'X-漂亮-Json:真正的'头的引入可以触发的格式手册卷要求的需求。
(测试轨3.2.8-5.0.0中,红宝石1.9.3-的2.2.0,Linux)
的 <pre>
标记在HTML,用 JSON.pretty_generate
, 将呈现id漂亮你的看法。我很高兴我的杰出的老板给我的这样的:
<% if @data.present? %>
<pre><%= JSON.pretty_generate(@data) %></pre>
<% end %>
如果你想:
- 美化所有外JSON的答复应用。
- 避免污染物#to_json/#as_jsonnow,来
- 避免分析/重新呈现JSON使用中间件(呸!)
- 这样做轨道的方式!
然后...替代ActionController::渲染书!只是添加以下代码你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
检查了 awesome_print.分析id string到红宝石的散列,然后显示它与awesome_print像这样:
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也将增加一些色彩,叠溢不会告诉你:)
倾倒的一个Email目叉(在轨控制台):
pp User.first.as_json
# => {
"id" => 1,
"first_name" => "Polar",
"last_name" => "Bear"
}
如果你的(像I)发现的 pretty_generate
选择建成红宝石的JSON图书馆不是"漂亮的"不够的,我建议我自己 NeatJSON
宝石你的格式。
使用它 gem install neatjson
然后再用 JSON.neat_generate
而不是的 JSON.pretty_generate
.
像的红宝石的 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?"}
]
}
它还支持各种各样的 格式的选择 为进一步定制你的输出。例如,有多少空间之前/后的冒号?前/后的逗号?括号内的数组和对象?你想排序的钥匙你的对象?你想冒号来所有被排队?
使用 <pre>
html代码和 pretty_generate
是良好的把戏:
<%
require 'json'
hash = JSON[{hey: "test", num: [{one: 1, two: 2, threes: [{three: 3, tthree: 33}]}]}.to_json]
%>
<pre>
<%= JSON.pretty_generate(hash) %>
</pre>
这里是一个中间解决方案所作的修改 这个优秀的答案通过@gertas.这个方案是不轨的具体--它应该与任何架应用程序。
中间件技术,这里使用,使用#每个,是在解释 ASCIIcasts151:架中间 通过Eifion贝德福德。
这个代码中 应用程序/中间/pretty_json_response.rb:
class PrettyJsonResponse
def initialize(app)
@app = app
end
def call(env)
@status, @headers, @response = @app.call(env)
[@status, @headers, self]
end
def each(&block)
@response.each do |body|
if @headers["Content-Type"] =~ /^application\/json/
body = pretty_print(body)
end
block.call(body)
end
end
private
def pretty_print(json)
obj = JSON.parse(json)
JSON.pretty_unparse(obj)
end
end
来打开它,添加这config/环境/测试。rb和config/环境/发展。rb:
config.middleware.use "PrettyJsonResponse"
作为@gertas警告说,在他的版本的这一解决方案,避免使用它在生产。这有点缓慢。
测试与轨4.1.6.
#At Controller
def branch
@data = Model.all
render json: JSON.pretty_generate(@data.as_json)
end
这是我的解决方案,我来自其他员额,在我自己的搜索。
这可以让你送pp和jj输出的文件作为必要的。
require "pp"
require "json"
class File
def pp(*objs)
objs.each {|obj|
PP.pp(obj, self)
}
objs.size <= 1 ? objs.first : objs
end
def jj(*objs)
objs.each {|obj|
obj = JSON.parse(obj.to_json)
self.puts JSON.pretty_generate(obj)
}
objs.size <= 1 ? objs.first : objs
end
end
test_object = { :name => { first: "Christopher", last: "Mullins" }, :grades => [ "English" => "B+", "Algebra" => "A+" ] }
test_json_object = JSON.parse(test_object.to_json)
File.open("log/object_dump.txt", "w") do |file|
file.pp(test_object)
end
File.open("log/json_dump.txt", "w") do |file|
file.jj(test_json_object)
end
我已经使用了gem CodeRay,它工作得很好。该格式包括颜色和它认识到很多不同的格式。
我已经用它在一个宝石,可用于轨道调试Api,它工作得很好。
顺便说一下,宝石被命名为'api_explorer'(http://www.github.com/toptierlabs/api_explorer)
如果你找到迅速实施这一轨道控制器的行动,发送一JSON响应:
def index
my_json = '{ "key": "value" }'
render json: JSON.pretty_generate( JSON.parse my_json )
end
我用以下,因为我找到标题,状况。用作输出 一组。该呼吁程序被破坏了建议从railscasts介绍: http://railscasts.com/episodes/151-rack-middleware?autoplay=true
class LogJson
def initialize(app)
@app = app
end
def call(env)
dup._call(env)
end
def _call(env)
@status, @headers, @response = @app.call(env)
[@status, @headers, self]
end
def each(&block)
if @headers["Content-Type"] =~ /^application\/json/
obj = JSON.parse(@response.body)
pretty_str = JSON.pretty_unparse(obj)
@headers["Content-Length"] = Rack::Utils.bytesize(pretty_str).to_s
Rails.logger.info ("HTTP Headers: #{ @headers } ")
Rails.logger.info ("HTTP Status: #{ @status } ")
Rails.logger.info ("JSON Response: #{ pretty_str} ")
end
@response.each(&block)
end
end
如果您使用 RABL 你可以配置,它作为描述 在这里, 使用手机中。pretty_generate:
class PrettyJson
def self.dump(object)
JSON.pretty_generate(object, {:indent => " "})
end
end
Rabl.configure do |config|
...
config.json_engine = PrettyJson if Rails.env.development?
...
end
一个问题与使用手机中。pretty_generate是,"}"结束验证程序将不再是高兴与你datetime strings.你可以修复那些在你的config/初始化/rabl_config.rb:
ActiveSupport::TimeWithZone.class_eval do
alias_method :orig_to_s, :to_s
def to_s(format = :default)
format == :default ? iso8601 : orig_to_s(format)
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
漂亮的打印变体:
my_object = { :array => [1, 2, 3, { :sample => "hash"}, 44455, 677778, 9900 ], :foo => "bar", rrr: {"pid": 63, "state": false}}
puts my_object.as_json.pretty_inspect.gsub('=>', ': ')
结果是:
{"array": [1, 2, 3, {"sample": "hash"}, 44455, 677778, 9900],
"foo": "bar",
"rrr": {"pid": 63, "state": false}}