Ruby on rails 如何";“漂亮”;在RubyonRails中格式化JSON输出
我希望我在RubyonRails中的JSON输出是“漂亮的”或格式良好的 现在,我调用Ruby on rails 如何";“漂亮”;在RubyonRails中格式化JSON输出,ruby-on-rails,ruby,json,pretty-print,Ruby On Rails,Ruby,Json,Pretty Print,我希望我在RubyonRails中的JSON输出是“漂亮的”或格式良好的 现在,我调用到_json,我的json都在一行上。有时很难看出JSON输出流中是否存在问题 有没有办法配置使我的JSON在Rails中变得“漂亮”或格式良好?使用JSON更高版本中内置的pretty\u generate()函数。例如: require 'json' my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar
到_json
,我的json都在一行上。有时很难看出JSON输出流中是否存在问题
有没有办法配置使我的JSON在Rails中变得“漂亮”或格式良好?使用JSON更高版本中内置的
pretty\u 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"
}
感谢Rack中间件和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
上面的代码应该放在Rails项目的app/middleware/pretty_json_response.rb中。
最后一步是在config/environments/development.rb
中注册中间件:
config.middleware.use PrettyJsonResponse
我不建议在production.rb中使用它。JSON重分类可能会降低生产应用程序的响应时间和吞吐量。最终,可能会引入额外的逻辑,如“X-Pretty-Json:true”头,以触发按需手动curl请求的格式设置
(使用Rails 3.2.8-5.0.0、Ruby 1.9.3-2.2.0、Linux进行了测试)这是我的解决方案,我在自己的搜索过程中从其他帖子中获得
这允许您根据需要将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
需要“pp”
需要“json”
类文件
def pp(*objs)
objs.each{| obj|
PP.PP(obj,self)
}
objs.size[“英语”=>“B+”,“代数”=>“A+”]}
test_json_object=json.parse(test_object.to_json)
打开(“log/object_dump.txt”,“w”)do|文件|
pp文件(测试对象)
结束
打开(“log/json_dump.txt”,“w”)do|文件|
jj(test_json_对象)
结束
该
<% if @data.present? %>
<pre><%= JSON.pretty_generate(@data) %></pre>
<% end %>
我使用了gem CodeRay,它工作得很好。该格式包括颜色,可识别许多不同的格式
我已经在一个可以用来调试rails API的gem上使用了它,它运行得非常好
顺便说一句,gem名为'api_explorer'()我使用以下内容,因为我发现标题、状态和JSON输出非常有用
一套。根据railscasts演示文稿中的建议,在以下地点展开呼叫程序:
将ActiveRecord对象转储到JSON(在Rails控制台中):
如果您想:
自动美化应用程序中所有传出的JSON响应
避免污染对象#to_json/#as_json
避免使用中间件解析/重新呈现JSON(恶心!)
按轨道走李>
然后。。。替换JSON的ActionController::Renderer!只需将以下代码添加到ApplicationController:
config.middleware.use "PrettyJsonResponse"
下面是一个从中修改的中间件解决方案。此解决方案不是特定于Rails的——它应该适用于任何机架应用程序
Eifion Bedford在上解释了这里使用的中间件技术,使用了#each
此代码位于app/middleware/pretty_json_response.rb中:
要打开它,请将其添加到config/environments/test.rb和config/environments/development.rb:
JSON.neat_generate
正如@gertas在其版本中警告的那样,避免在生产中使用它。有点慢
使用Rails 4.1.6进行测试。如果您发现Ruby的JSON库中内置的pretty_generate
选项不够“漂亮”,我建议您使用我自己的gem进行格式化
要使用它:
JSON.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
而不是
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
像Ruby的pp
一样,它将在合适的时候将对象和数组放在一行上,但根据需要将它们包装成多行。例如:
require 'json'
my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_object)
{
“navigation.createroute.poi”:[
{“文本”:“躺在希尔顿的球场上”,“params”:{“poi”:“希尔顿”},
{“文本”:“带我去机场”,“参数”:{“poi”:“机场”},
{“文本”:“让我们转到IHOP”,“参数”:{“poi”:“IHOP”},
{“文本”:“演示如何到达地中海”,“参数”:{“poi”:“地中海”},
{“text”:“创建到Arby's的路由”,“params”:{“poi”:“Arby's”},
{
“文本”:“去机场旁边的希尔顿酒店”,
“params”:{“poi”:“希尔顿”,“地点”:“机场”}
},
{
“文本”:“带我去弗雷斯诺的南联盟”,
“params”:{“poi”:“Fry's”,“位置”:“Fresno”}
}
],
“navigation.eta”:[
{“文本”:“我们什么时候到那里?”},
{“文本”:“我什么时候到?”},
{“文本”:“我什么时候到达目的地?”},
{“文本”:“我什么时候到达目的地?”},
{“文本”:“我什么时候到达?”}
]
}
它还支持多种方法来进一步自定义输出。例如,冒号前后有多少空格?逗号之前/之后?在数组和对象的括号内?是否要对对象的键进行排序?是否要将冒号全部对齐?如果您正在使用,可以按照所述配置它以使用JSON.pretty\u生成:
# 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
使用JSON.pretty_generate的一个问题是,JSON模式验证器将不再满意您的日期时间字符串。您可以使用以下方法修复config/initializers/rabl_config.rb中的问题:
def index
my_json = '{ "key": "value" }'
render json: JSON.pretty_generate( JSON.parse my_json )
end
#使用示例:
a_hash={user_info:{键入:“查询服务”,电子邮件:my@email.com,电话:“+79876543322”},汽车制造商:[“宝马”,“三菱”],汽车型号:[宝马:{型号:“1er”,制造年份:2006},三菱:{型号:“帕杰罗”,制造年份:1997}]
pretty\u html=a_hash.pretty\u html
#将此模块包括到您的LIB中:
模块MyPrettyPrint
def pretty_html缩进=0
result=“”
如果self.class==散列
self.each do |键、值|
结果+=“#{key}:#{[Array,Hash].include?(value.class)value.pretty_html(indent+1):value}”
结束
elsif self.class==数组
结果=“[#{self.join(',')}”
结束
“#{result}”
结束
结束
类散列
包括我的预打印
结束
类数组
包括我的预打印
结束
如果您希望快速实现
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
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
def index
my_json = '{ "key": "value" }'
render json: JSON.pretty_generate( JSON.parse my_json )
end
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
}
}
<%
require 'json'
hash = JSON[{hey: "test", num: [{one: 1, two: 2, threes: [{three: 3, tthree: 33}]}]}.to_json]
%>
<pre>
<%= JSON.pretty_generate(hash) %>
</pre>
#At Controller
def branch
@data = Model.all
render json: JSON.pretty_generate(@data.as_json)
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}}
my_json = '{ "name":"John", "age":30, "car":null }'
puts JSON.pretty_generate(JSON.parse(my_json))
core dev 1555:0> my_json = '{ "name":"John", "age":30, "car":null }'
=> "{ \"name\":\"John\", \"age\":30, \"car\":null }"
core dev 1556:0> puts JSON.pretty_generate(JSON.parse(my_json))
{
"name": "John",
"age": 30,
"car": null
}
=> nil