ruby-on-rails-3jsonpretty-printjbuilder

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).


Solution

  • I think this is simpler,

    @package = Package.first
    
    json = JSON.parse(@blog.to_json)
    
    PP.pp(json)
    
    {"id_to_s"=>"5222675dbc11149e3a000002",
     "title"=>"Package Title",
     "version"=>"0.1.1",
     "comment"=>
      {"user"=>"Joe",
       "description"=>"Joe's comment"},
     "assets"=>
      [{"id_to_s"=>"522a4620fa451436f4000001",
        "_type"=>"Illustration",
        "start"=>0,
        "stop"=>100,
        "caption"=>"mountain climbing"},
       {"id_to_s"=>"522a56a6fa4514523a000001",
        "_type"=>"Illustration",
        "start"=>200,
        "stop"=>300,
        "caption"=>"airport"},
       {"id_to_s"=>"522a6a0ffa4514a30e000002",
        "_type"=>"Illustration",
        "start"=>400,
        "stop"=>600,
        "caption"=>"doc"},
       {"id_to_s"=>"522aa46bbc1114551f000001",
        "_type"=>"Illustration",
        "start"=>nil,
        "stop"=>nil,
        "caption"=>nil},
       {"id_to_s"=>"522aa47fbc1114551f000002",
        "_type"=>"Illustration",
        "start"=>10,
        "stop"=>30,
        "caption"=>"asdflkjsd"}]}
    

    Or, the quicker one-liner,

    PP.pp JSON.parse Blog.first.to_json