Q:

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

I have something like:
{"a":"1","b":"2","c":"3","asefw":"dfsef"}

I want to print it out in a view. What's the best way to do that?
I tried parsing it as a JSON object and using JSON.stringify, but it seems to mess up indentation.
Any advice? I don't mind a JavaScript solution.

A:

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>

A:

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.

A:

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

