我希望我在Ruby on Rails中的JSON输出“漂亮”或格式化得很好。
现在,我调用to_json,我的JSON都在一行上。有时,很难看出JSON输出流中是否有问题。
有办法配置,使我的JSON“漂亮”或很好的格式在Rails?
我希望我在Ruby on Rails中的JSON输出“漂亮”或格式化得很好。
现在,我调用to_json,我的JSON都在一行上。有时,很难看出JSON输出流中是否有问题。
有办法配置,使我的JSON“漂亮”或很好的格式在Rails?
当前回答
# 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_json = '{ "name":"John", "age":30, "car":null }'
puts JSON.pretty_generate(JSON.parse(my_json))
Rails控制台示例:
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
使用pretty_generate()函数,该函数内置于JSON的后期版本中。例如:
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"
}
# 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控制台中有一个JSON对象,并希望在控制台中很好地显示它(而不是像大量连接的字符串那样显示),它简单如:
data.as_json
如果你正在使用RABL,你可以使用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
使用JSON的一个问题。pretty_generate是JSON模式验证器将不再满意您的datetime字符串。你可以在config/initializers/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