Jak" ładnie " sformatować wyjście JSON w Ruby on Rails?

Chciałbym, aby moje wyjście JSON w Ruby on Rails było "ładne" lub ładnie sformatowane.

W tej chwili, dzwonię {[0] } i mój JSON jest na jednej linii. Czasami może to być trudne do sprawdzenia, czy jest problem w strumieniu wyjściowym JSON.

Czy jest sposób na konfigurację lub sposób, aby mój JSON był "ładny" lub ładnie sformatowany w Rails?

Author: the Tin Man, 2008-09-17

16 answers

Użyj funkcji pretty_generate(), wbudowanej w późniejsze wersje JSON. Na przykład:

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

Co daje:

{
  "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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-25 22:33:27

Dzięki Rack Middleware i Rails 3 możesz wydrukować ładny JSON dla każdego żądania bez zmiany kontrolera aplikacji. Napisałem taki fragment middleware ' a i dostaję ładnie wydrukowany JSON w przeglądarce i curl output.

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

Powyższy kod powinien być umieszczony w app/middleware/pretty_json_response.rb Twojego projektu Rails. I ostatnim krokiem jest zarejestrowanie middleware w config/environments/development.rb:

config.middleware.use PrettyJsonResponse

Nie polecam go używać w production.rb. Naprawa JSON może obniżyć czas reakcji i przepustowość aplikacji produkcyjnej. Ostatecznie można wprowadzić dodatkową logikę, taką jak nagłówek 'X-Pretty-JSON: true', aby wyzwalać formatowanie ręcznych żądań zwijania na żądanie.

(testowane z 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-10 20:25:21

Znacznik <pre> w HTML, używany z JSON.pretty_generate, wyrenderuje JSON w Twoim widoku. Byłam taka szczęśliwa, kiedy mój znakomity szef pokazał mi to:

<% 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/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-27 01:47:31

Jeśli chcesz:

  1. popraw wszystkie wychodzące odpowiedzi JSON z aplikacji automatycznie.
  2. unikaj zanieczyszczania obiektu#to_json/ # as_json
  3. unikaj parsowania / ponownego renderowania JSON przy użyciu middleware (YUCK!)
  4. Zrób to po szynach!
Więc ... zastąp ActionController:: Renderer dla JSON! Wystarczy dodać następujący kod do kontrolera 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/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-11 16:42:29

Sprawdź awesome_print . Następnie wyświetlamy go za pomocą awesome_print w następujący sposób:

require "awesome_print"
require "json"

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

ap(JSON.parse(json))

Z powyższego widać:

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

Awesome_print również doda jakiś kolor, którego przepełnienie stosu nie pokaże:)

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-02 19:39:31

Wrzucanie obiektu ActiveRecord do JSON (w konsoli 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/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-04 13:31:48

Jeśli (jak ja) stwierdzisz, że opcja pretty_generate wbudowana w bibliotekę JSON Rubiego nie jest wystarczająco "ładna", polecam moją własną NeatJSON klejnot do formatowania.

Aby go użyć gem install neatjson, a następnie użyć JSON.neat_generate zamiast JSON.pretty_generate.

Podobnie jak Ruby pp będzie przechowywać obiekty i tablice w jednej linii, gdy będą pasować, ale zawijać do wielu w razie potrzeby. Na przykład:

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

Obsługuje również wiele opcji formatowania , aby jeszcze bardziej dostosować swoje wyniki. Na przykład, ile spacje przed / po dwukropkach? Przed / po przecinkach? Wewnątrz nawiasów tablic i obiektów? Czy chcesz posortować klucze swojego obiektu? Chcesz, żeby wszystkie dwukropki były ustawione?

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-16 16:01:09

Używanie <pre> kodu html i pretty_generate jest dobrą sztuczką:

<%
  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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-03 01:50:54

Oto rozwiązanie middleware zmodyfikowane z tej doskonałej odpowiedzi autorstwa @gertas . To rozwiązanie nie jest specyficzne dla szyn-powinno działać z każdą aplikacją Rack.

[[2]}Technika middleware użyta tutaj, przy użyciu #each, jest wyjaśniona w ASCIIcasts 151: Rack Middleware Przez Eifiona Bedforda.

Ten kod wchodzi w 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

Aby go włączyć, dodaj go do config / environments / test.rb i config / environments / development.rb:

config.middleware.use "PrettyJsonResponse"

Jak ostrzega @gertas w swojej wersji tego rozwiązania, unikaj używania go w produkcji. Jest trochę powolny.

Testowane z Rails 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/doraprojects.net/template/agent.layouts/content.php on line 54
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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-16 11:43:24

Oto moje rozwiązanie, które zaczerpnąłem z innych postów podczas własnych poszukiwań.

Pozwala to na wysłanie wyjścia pp i jj do pliku w razie potrzeby.

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/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-23 04:01:27

Użyłem gem CodeRay i działa całkiem dobrze. Format zawiera kolory i rozpoznaje wiele różnych formatów.

Użyłem go na gem, który może być używany do debugowania interfejsów API rails i działa całkiem dobrze.

Przy okazji, klejnot nazywa się " 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/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-21 22:08:20

Jeśli chcesz szybko zaimplementować to w akcji kontrolera Rails, aby wysłać odpowiedź 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-17 00:38:07

Używam następujących, ponieważ uważam, że nagłówki, status i wyjście JSON są przydatne jako zestaw. Procedura połączenia jest rozwiązana na podstawie zalecenia z prezentacji railscasts pod adresem: 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/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-01 04:05:39

Jeśli używasz RABL możesz skonfigurować go zgodnie z opisem TUTAJ Aby używać 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

Problem z używaniem JSON.pretty_generate polega na tym, że walidatory schematu JSON nie będą już zadowolone z ciągów datetime. Możesz je naprawić w swoim config/initializers / rabl_config.RB z:

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/doraprojects.net/template/agent.layouts/content.php on line 54
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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-30 07:15:54