Domanda

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 può essere difficile vedere se c'è un problema nel flusso di output JSON.

Esiste un modo per configurare o un metodo per rendere il mio JSON "carino" o ben formattato in Rails?

È stato utile?

Soluzione

Usa il pretty_generate() funzione, incorporata 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)

Il che ti porta:

{
  "array": [
    1,
    2,
    3,
    {
      "sample": "hash"
    }
  ],
  "foo": "bar"
}

Altri suggerimenti

Grazie a Rack Middleware e Rails 3 puoi produrre un bel JSON per ogni richiesta senza cambiare alcun controller della tua app.Ho scritto questo snippet middleware e ottengo JSON ben stampato nel browser e curl produzione.

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 app/middleware/pretty_json_response.rb del tuo progetto Rails.E il passaggio finale è registrare il middleware config/environments/development.rb:

config.middleware.use PrettyJsonResponse

Non consiglio di usarlo production.rb.L'analisi JSON potrebbe ridurre i tempi di risposta e la velocità effettiva dell'app di produzione.Eventualmente logica extra come "X-Pretty-Json:L'intestazione true' può essere introdotta per attivare la formattazione per le richieste di curl manuali su richiesta.

(Testato con Rails 3.2.8-5.0.0, Ruby 1.9.3-2.2.0, Linux)

IL <pre> tag in HTML, utilizzato con JSON.pretty_generate, renderà il JSON carino secondo te.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:

  1. Migliora automaticamente tutte le risposte JSON in uscita dalla tua app.
  2. Evitare di inquinare Object#to_json/#as_json
  3. Evita l'analisi/il nuovo rendering di JSON utilizzando il middleware (YUCK!)
  4. Fallo nel MODO RAILS!

Poi ...sostituisci ActionController::Renderer con 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

Guardare awesome_print.Analizza la stringa JSON in un Ruby Hash, 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à :)

Dump di un oggetto ActiveRecord su JSON (nella console Rails):

pp User.first.as_json

# => {
 "id" => 1,
 "first_name" => "Polar",
 "last_name" => "Bear"
}

Se tu (come me) scopri che il pretty_generate L'opzione integrata nella libreria JSON di Ruby non è abbastanza "carina", consiglio la mia NeatJSON gioiello per la tua formattazione.

Per usarlo gem install neatjson e poi utilizzare JSON.neat_generate invece di JSON.pretty_generate.

Come quello di Ruby pp manterrà gli oggetti e gli array su una riga quando si adattano, ma li avvolgerà su più righe secondo 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 l'output.Ad esempio, quanti spazi prima/dopo i due punti?Prima/dopo la virgola?All'interno delle parentesi di array e oggetti?Vuoi ordinare le chiavi del tuo oggetto?Vuoi che i due punti siano tutti allineati?

Utilizzando <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>

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 utilizzata qui, utilizzando #each, è spiegata in ASCIIcast 151:Middleware per rack di Eifion Bedford.

Questo codice va dentro 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 attivarlo, aggiungilo a config/environments/test.rb e config/environments/development.rb:

config.middleware.use "PrettyJsonResponse"

Come avverte @gertas nella sua versione di questa soluzione, evitare di utilizzarla 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

Ecco la mia soluzione che ho derivato 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

Ho usato la gemma CodeRay e funziona abbastanza bene.Il formato include colori e riconosce molti formati diversi.

L'ho usato su un gem che può essere utilizzato per il debug delle API dei rail e funziona abbastanza 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

Uso quanto segue mentre trovo le intestazioni, lo stato e l'output JSON utili come set.La routine di chiamata è stata interrotta su raccomandazione di una presentazione di railscasts all'indirizzo: 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 utilizzare 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 risolverli nel tuo config/initializers/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: "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

Variante di stampa carina:

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}}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top