I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted.
Right now, I call to_json
and my JSON is all on one line. At times this can be difficult to see if there is a problem in the JSON output stream.
Is there way to configure or a method to make my JSON "pretty" or nicely formatted in Rails?
Using
<pre>
html code andpretty_generate
is good trick:If you (like I) find that the
pretty_generate
option built into Ruby's JSON library is not "pretty" enough, I recommend my ownNeatJSON
gem for your formatting.To use it
gem install neatjson
and then useJSON.neat_generate
instead ofJSON.pretty_generate
.Like Ruby's
pp
it will keep objects and arrays on one line when they fit, but wrap to multiple as needed. For example:It also supports a variety of formatting options to further customize your output. For example, how many spaces before/after colons? Before/after commas? Inside the brackets of arrays and objects? Do you want to sort the keys of your object? Do you want the colons to all be lined up?
Check out awesome_print. Parse the JSON string into a Ruby Hash, then display it with awesome_print like so:
With the above, you'll see:
awesome_print will also add some color that Stack Overflow won't show you :)
If you are using RABL you can configure it as described here to use JSON.pretty_generate:
A problem with using JSON.pretty_generate is that JSON schema validators will no longer be happy with your datetime strings. You can fix those in your config/initializers/rabl_config.rb with:
Use the
pretty_generate()
function, built into later versions of JSON. For example:Which gets you: