¿Cómo puedo formatear "pretty" mi salida JSON en Ruby on Rails?


Me gustaría que mi salida JSON en Ruby on Rails fuera "bonita" o bien formateada.

Ahora mismo, llamo to_json y mi JSON está todo en una línea. A veces esto puede ser difícil de ver si hay un problema en el flujo de salida JSON.

¿Hay forma de configurar o un método para hacer que mi JSON sea "bonito" o bien formateado en Rails?

Author: the Tin Man, 2008-09-17

16 answers

Utilice la función pretty_generate(), integrada en versiones posteriores de JSON. Por ejemplo:

require 'json'
my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_object)

Que te lleva:

{
  "array": [
    1,
    2,
    3,
    {
      "sample": "hash"
    }
  ],
  "foo": "bar"
}
 859
Author: jpatokal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-25 22:33:27

Gracias a Rack Middleware y Rails 3 puedes generar un bonito JSON para cada petición sin cambiar ningún controlador de tu app. He escrito este fragmento de middleware y obtengo JSON muy bien impreso en el navegador y la salida 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

El código anterior debe colocarse en app/middleware/pretty_json_response.rb de su proyecto Rails. Y el paso final es registrar el middleware en config/environments/development.rb:

config.middleware.use PrettyJsonResponse

Yo no recomiendo usarlo en production.rb. El reparsing JSON puede degradar el tiempo de respuesta y rendimiento de su aplicación de producción. Eventualmente se puede introducir una lógica adicional como el encabezado 'X-Pretty-Json: true' para activar el formato de las solicitudes de curl manual bajo demanda.

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

 68
Author: gertas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-10 20:25:21

La etiqueta <pre> en HTML, utilizada con JSON.pretty_generate, hará que el JSON sea bonito en su vista. Estaba tan feliz cuando mi ilustre jefe me mostró esto:

<% if [email protected]? %>
   <pre><%= JSON.pretty_generate(@data) %></pre>
<% end %>
 59
Author: Roger Garza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-27 01:47:31

Si quieres:

  1. Embellece automáticamente todas las respuestas JSON salientes de tu app.
  2. Evite contaminar el objeto # to_json / # as_json
  3. Evite analizar / re-renderizar JSON usando middleware (YUCK!)
  4. ¡Hazlo de la MANERA de los RIELES!

Entonces ... reemplace el ActionController:: Renderer para JSON! Simplemente agregue el siguiente código a su 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
 20
Author: Ed Lebert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-11 16:42:29

Echa un vistazo a awesome_print. Analice la cadena JSON en un Hash Ruby, luego muéstrela con awesome_print de la siguiente manera:

require "awesome_print"
require "json"

json = '{"holy": ["nested", "json"], "batman!": {"a": 1, "b": 2}}'

ap(JSON.parse(json))

Con lo anterior, verás:

{
  "holy" => [
    [0] "nested",
    [1] "json"
  ],
  "batman!" => {
    "a" => 1,
    "b" => 2
  }
}

Awesome_print también agregará un color que Stack Overflow no te mostrará:)

 10
Author: Synthead,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-02 19:39:31

Volcando un objeto ActiveRecord a JSON (en la consola Rails):

pp User.first.as_json

# => {
 "id" => 1,
 "first_name" => "Polar",
 "last_name" => "Bear"
}
 9
Author: Thomas Klemm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-04 13:31:48

Si (como yo) encuentras que la opción pretty_generate integrada en la biblioteca JSON de Ruby no es lo suficientemente" bonita", te recomiendo la mía NeatJSON gema para su formato.

Para usarlo gem install neatjson y luego usar JSON.neat_generate en lugar de JSON.pretty_generate.

Al igual que el pp de Ruby, mantendrá los objetos y matrices en una línea cuando encajen, pero se ajustarán a múltiples según sea necesario. Por ejemplo:

{
  "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?"}
  ]
}

También admite una variedad de opciones de formato para personalizar aún más su salida. Por ejemplo, ¿cuántos espacios antes / después de dos puntos? Antes/después de las comas? ¿Dentro de los corchetes de matrices y objetos? ¿Quieres ordenar las llaves de tu objeto? ¿Quieres que todos los colon estén alineados?

 9
Author: Phrogz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-16 16:01:09

Usar <pre> código html y pretty_generate es un buen truco:

<%
  require 'json'

  hash = JSON[{hey: "test", num: [{one: 1, two: 2, threes: [{three: 3, tthree: 33}]}]}.to_json] 
%>

<pre>
  <%=  JSON.pretty_generate(hash) %>
</pre>
 9
Author: araratan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-03 01:50:54

Aquí hay una solución de middleware modificada de esta excelente respuesta de @gertas. Esta solución no es específica de Rails should debería funcionar con cualquier aplicación de Rack.

La técnica de middleware utilizada aquí, usando #each, se explica en ASCIIcasts 151: Rack Middleware por Eifion Bedford.

Este código va en 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

Para activarlo, añada esto a config/environments/test.rb y config / environments / development.rb:

config.middleware.use "PrettyJsonResponse"

Como advierte @gertas en su versión de esta solución, evite usarla en producción. Es algo lento.

Probado con Rieles 4.1.6.

 6
Author: Wayne Conrad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:47
#At Controller
def branch
    @data = Model.all
    render json: JSON.pretty_generate(@data.as_json)
end
 4
Author: Буянбат Чойжилсүрэн,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-16 11:43:24

Aquí está mi solución que derivé de otras publicaciones durante mi propia búsqueda.

Esto le permite enviar la salida pp y jj a un archivo según sea necesario.

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
 2
Author: Christopher Mullins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-23 04:01:27

He usado la gema CodeRay y funciona bastante bien. El formato incluye colores y reconoce muchos formatos diferentes.

Lo he usado en una gema que se puede usar para depurar las API de rails y funciona bastante bien.

Por cierto, la gema se llama ' api_explorer '( http://www.github.com/toptierlabs/api_explorer )

 2
Author: Tony,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-21 22:08:20

Si está buscando implementar esto rápidamente en una acción del controlador Rails para enviar una respuesta JSON:

def index
  my_json = '{ "key": "value" }'
  render json: JSON.pretty_generate( JSON.parse my_json )
end
 2
Author: sealocal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-17 00:38:07

Utilizo lo siguiente para encontrar los encabezados, el estado y la salida JSON útiles como conjunto. La rutina de llamada se desglosa por recomendación de una presentación de railscasts en: 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
 1
Author: TheDadman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-01 04:05:39

Si está utilizando RABL puede configurarlo como se describe aquí para usar 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 el uso de JSON.pretty_generate es que los validadores de esquema JSON ya no estarán contentos con sus cadenas de fecha y hora. Puedes arreglarlos en tu 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
 1
Author: Jim Flood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-04 18:03:30

# 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
 1
Author: Sergio Belevskij,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-30 07:15:54