How do I pretty print a hash to a Rails view? How do I pretty print a hash to a Rails view? json json

How do I pretty print a hash to a Rails view?


How about:

require 'json'hash = JSON['{"a":"1","b":"2","c":"3","asefw":"dfsef"}']puts JSON.pretty_generate(hash)

Which outputs:

{  "a": "1",  "b": "2",  "c": "3",  "asefw": "dfsef"}

JSON.pretty_generate is more of a debugging tool than something I'd rely on when actually generating JSON to be sent to a browser. The "pretty" aspect also means "bloated" and "slower" because of the added whitespace, but it is good for diagnosing and comprehending what is in the structure so it might work well for your needs.

One thing to remember is that HTML, when rendered by a browser, has whitespace gobbled up, so whitespace runs disappear. To avoid that you have to wrap the JSON output in a <pre> block to preserve the whitespace and line-breaks. Something like this should work:

<pre>{  "a": "1",  "b": "2",  "c": "3",  "asefw": "dfsef"}</pre>


irb(main)> puts queried_object.pretty_inspect

From PrettyPrint, so may need to require 'pp' first for this to work.

This also works great for e.g. Rails.logger output.


<%= raw JSON.pretty_generate(hash).gsub(" "," ") %>