enjaku enjaku - 1 year ago 145
Ruby Question

ruby JSON.pretty_generate() doesn't work

I'm trying to print JSON data in a view in a 'pretty' human readable format. I have a controller:

def show
h = JSON.parse(RestClient.get("http://link_to_get_json"))
@json = JSON.pretty_generate(h)

and a simple view:

= @json

But all I see, when I load the page, is the same JSON I've got, not formatted. What do I do wrong?

Answer Source

JSON.pretty_generate inserts whitespace into the returned string.

If your'e dumping the string into an HTML document, all whitespace (such as newlines) is ignored, and rendered as a single space. In order to preserve whitespace, you need add a white-space: pre CSS style, or wrap the content in a <pre> tag.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download