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).
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!
# 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With