Vorrei che il mio output JSON in Ruby on Rails fosse "carino" o ben formattato.
In questo momento, chiamo to_json
e il mio JSON è tutto su una riga. A volte questo può essere difficile da vedere se c'è un problema nel flusso di output JSON.
C'è un modo per configurare o un metodo per rendere il mio JSON "carino" o ben formattato in Rails?
Usa la funzione pretty_generate()
, integrata nelle versioni successive di JSON. Per esempio:
require 'json'
my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_object)
Che ti prende:
{
"array": [
1,
2,
3,
{
"sample": "hash"
}
],
"foo": "bar"
}
Grazie a Rack Middleware e Rails 3 è possibile creare un bel JSON per ogni richiesta senza cambiare alcun controller della tua app. Ho scritto questo frammento di middleware e ottengo JSON ben stampato nel browser e output 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
Il codice sopra dovrebbe essere inserito in app/middleware/pretty_json_response.rb
del tuo progetto Rails. E il passo finale è registrare il middleware in config/environments/development.rb
:
config.middleware.use PrettyJsonResponse
Non consiglio di usarlo in production.rb
. Il reparsing JSON può ridurre i tempi di risposta e il throughput della tua app di produzione. Eventualmente è possibile introdurre una logica aggiuntiva come "X-Pretty-Json: true" per attivare la formattazione per le richieste di arricciatura manuale su richiesta.
(Testato con Rails 3.2.8-5.0.0, Ruby 1.9.3-2.2.0, Linux)
Il tag <pre>
in HTML, usato con JSON.pretty_generate
, renderà il JSON piuttosto carino nella tua vista. Ero così felice quando il mio illustre capo mi ha mostrato questo:
<% if @data.present? %>
<pre><%= JSON.pretty_generate(@data) %></pre>
<% end %>
Se lo desidera:
Quindi ... sostituisci ActionController :: Renderer per JSON! Basta aggiungere il seguente codice al tuo 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
Controlla awesome_print . Analizza la stringa JSON in un hash di Ruby, quindi visualizzala con awesome_print in questo modo:
require "awesome_print"
require "json"
json = '{"holy": ["nested", "json"], "batman!": {"a": 1, "b": 2}}'
ap(JSON.parse(json))
Con quanto sopra, vedrai:
{
"holy" => [
[0] "nested",
[1] "json"
],
"batman!" => {
"a" => 1,
"b" => 2
}
}
awesome_print aggiungerà anche del colore che Stack Overflow non ti mostrerà :)
Usare <pre>
codice html e pretty_generate
è un buon trucco:
<%
require 'json'
hash = JSON[{hey: "test", num: [{one: 1, two: 2, threes: [{three: 3, tthree: 33}]}]}.to_json]
%>
<pre>
<%= JSON.pretty_generate(hash) %>
</pre>
Scaricamento di un oggetto ActiveRecord su JSON (nella console di Rails):
pp User.first.as_json
# => {
"id" => 1,
"first_name" => "Polar",
"last_name" => "Bear"
}
Se tu (come I) trovi che l'opzione pretty_generate
incorporata nella libreria JSON di Ruby non è "abbastanza" abbastanza, consiglio il mio NeatJSON
NAME _ gem per la tua formattazione .
Per usarlo gem install neatjson
e quindi usare JSON.neat_generate
anziché JSON.pretty_generate
.
Come pp
di Ruby, manterrà gli oggetti e gli array su una riga quando si adattano, ma si avvolgeranno in multipli a seconda delle necessità. Per esempio:
{
"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?"}
]
}
Supporta anche una varietà di opzioni di formattazione per personalizzare ulteriormente il tuo output. Ad esempio, quanti spazi prima/dopo due punti? Prima/dopo le virgole? Dentro le parentesi di matrici e oggetti? Vuoi ordinare le chiavi del tuo oggetto? Vuoi che i due punti siano allineati?
Ecco una soluzione middleware modificata da questa eccellente risposta di @gertas . Questa soluzione non è specifica di Rails - dovrebbe funzionare con qualsiasi applicazione Rack.
La tecnica del middleware usata qui, usando #each, è spiegata in ASCIIcasts 151: Rack Middleware di Eifion Bedford.
Questo codice va in app/middleware/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
Per accenderlo, aggiungilo a config/environments/test.rb e config/environments/development.rb:
config.middleware.use "PrettyJsonResponse"
Come @gertas avverte nella sua versione di questa soluzione, evitare di usarlo in produzione. È un po 'lento.
Testato con Rails 4.1.6.
#At Controller
def branch
@data = Model.all
render json: JSON.pretty_generate(@data.as_json)
end
Ho usato la gemma CodeRay e funziona abbastanza bene. Il formato include i colori e riconosce molti formati diversi.
L'ho usato su una gemma che può essere usata per il debug delle API di Rails e funziona piuttosto bene.
A proposito, la gemma si chiama 'api_Explorer' ( http://www.github.com/toptierlabs/api_Explorer )
Se stai cercando di implementarlo rapidamente in un'azione del controller Rails per inviare una risposta JSON:
def index
my_json = '{ "key": "value" }'
render json: JSON.pretty_generate( JSON.parse my_json )
end
Ecco la mia soluzione che ho ricavato da altri post durante la mia ricerca.
Ciò consente di inviare l'output pp e jj a un file secondo necessità.
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
Io uso il seguente come trovo le intestazioni, lo stato e l'output JSON utili come set. La routine di chiamata è suddivisa su raccomandazione da una presentazione di railscast su: 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
Se stai usando RABL puoi configurarlo come descritto qui per usare 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
Un problema con l'utilizzo di JSON.pretty_generate è che i validatori dello schema JSON non saranno più soddisfatti delle stringhe datetime. Puoi sistemare quelli nella tua configurazione/inizializzatori/rabl_config.rb con:
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: "[email protected]", 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
Bella variante di stampa:
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('=>', ': ')
Risultato:
{"array": [1, 2, 3, {"sample": "hash"}, 44455, 677778, 9900],
"foo": "bar",
"rrr": {"pid": 63, "state": false}}