Pregunta

Me gustaría que mi salida JSON en Ruby on Rails fuera "bonita" o tuviera un buen formato.

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

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

¿Fue útil?

Solución

Utilizar el pretty_generate() función, 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)

Lo que te lleva:

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

Otros consejos

Gracias a Rack Middleware y Rails 3, puedes generar JSON bonito para cada solicitud sin cambiar ningún controlador de tu aplicación.He escrito dicho fragmento de middleware y obtengo un JSON muy bien impreso en el navegador y curl producción.

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 último paso es registrar el middleware en config/environments/development.rb:

config.middleware.use PrettyJsonResponse

No recomiendo usarlo en production.rb.El análisis JSON puede degradar el tiempo de respuesta y el rendimiento de su aplicación de producción.Eventualmente lógica adicional como 'X-Pretty-Json:Se puede introducir el encabezado "true" para activar el formato para solicitudes de curl manual a pedido.

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

El <pre> etiqueta en HTML, utilizada con JSON.pretty_generate, hará que el JSON sea bonito a tu vista.Me alegré mucho cuando mi ilustre jefe me mostró esto:

<% if @data.present? %>
   <pre><%= JSON.pretty_generate(@data) %></pre>
<% end %>

Si quieres:

  1. Embellezca todas las respuestas JSON salientes de su aplicación automáticamente.
  2. Evite contaminar el Objeto#to_json/#as_json
  3. Evite analizar/volver a renderizar JSON usando middleware (¡QUÉ!)
  4. ¡Hazlo al estilo RAILS!

Entonces ...¡Reemplace ActionController::Renderer por 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

Verificar impresionante_impresión.Analice la cadena JSON en Ruby Hash y luego muéstrela con awesome_print de esta 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á algo de color que Stack Overflow no te mostrará :)

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

pp User.first.as_json

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

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

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

como el de rubí pp mantendrá los objetos y las matrices en una línea cuando encajen, pero se ajustará a varias 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 soporta una variedad de opciones de formato para personalizar aún más su salida.Por ejemplo, ¿cuántos espacios antes/después de los dos puntos?¿Antes/después de comas?¿Dentro de los corchetes de matrices y objetos?¿Quieres ordenar las claves de tu objeto?¿Quieres que todos los dos puntos estén alineados?

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

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

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

Este código entra aplicación/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, agregue 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 Rails 4.1.6.

#At Controller
def branch
    @data = Model.all
    render json: JSON.pretty_generate(@data.as_json)
end

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

Esto le permite enviar la salida de 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

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 API de rieles y funciona bastante bien.

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

Si buscas 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

Utilizo lo siguiente, ya que encuentro los encabezados, el estado y la salida de JSON útil como un conjunto.La rutina de llamadas 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

Si estas usando RABL puedes 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 esquemas 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

# 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

Bonita variante de impresión:

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('=>', ': ')

Resultado:

{"array": [1, 2, 3, {"sample": "hash"}, 44455, 677778, 9900],
 "foo": "bar",
 "rrr": {"pid": 63, "state": false}}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top