Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 210
chintanparikh Avatar asked Jun 25 '13 04:06

chintanparikh


People also ask

How do you access the Hash in Ruby?

In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.

How do you write a Hash in Ruby?

In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.

What is a Hash in rails?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.

Is Hash in Ruby ordered?

We found a post on the Ruby mailing list from a couple of years ago which pointed out that from Ruby 1.9 the order is in fact maintained. Hashes are inherently unordered. Hashes provide amortized O(1) insertion and retrieval of elements by key, and that's it. If you need an ordered set of pairs, use an array of arrays.


1 Answers

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>
like image 194
the Tin Man Avatar answered Nov 01 '22 13:11

the Tin Man