Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty Print JSON generated with a jbuilder template in Rails 3.2.8

Anyone have a way to pretty print JSON output from jbuilder?

I can pretty print JSON generated within a controller action with something like:

JSON.pretty_generate(some_json_object) 

but once I pass off to a jbuilder template, I'm not aware of a way to have that output pretty printed.

Right now, my action method's render statement is simple:

render formats: :json    

And this successfully forces a rendering with jbuilder, regardless of input format type specified (which is my desired behavior).

like image 747
idStar Avatar asked Oct 29 '12 19:10

idStar


2 Answers

I found a way to do this:

 json_string = render_to_string formats: :json    
 json_object = JSON.parse(json_string)     
 render :json => JSON.pretty_generate(json_object)     

Again, this assumes there is a jbuilder template for this action, which will create the initial json, which gets rendered to a string, back into a json object and then passed to pretty_generate().

It's a bit circuitous, but it works. I'm of course, totally open to tighter implementations!

like image 152
idStar Avatar answered Sep 17 '22 22:09

idStar


# config/initializers/jbuilder_prettify.rb
require "jbuilder"

class Jbuilder
  ##
  # Allows you to set @prettify manually in your .jbuilder files. 
  # Example: 
  #   json.prettify true
  #   json.prettify false 
  #  
  attr_accessor :prettify

  alias_method :_original_target, :target!

  ##
  # A shortcut to enabling prettify.
  # Example:
  #   json.prettify!
  #
  def prettify!
    @prettify = true
  end

  def target!
    @prettify ? ::JSON.pretty_generate(@attributes) : _original_target
  end
end

# app/views/api/v1/users/show.json.jbuilder
json.prettify! if %w(1 yes true).include?(params["pretty"])

json.( @user, :id, :name, :created_at, :updated_at )

https://github.com/rails/jbuilder/issues/195#issuecomment-44440569

like image 37
Mark Murphy Avatar answered Sep 17 '22 22:09

Mark Murphy