views:

4984

answers:

5

I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted. Right now, I call the to_json method 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 RoR?

Thanks.

A: 

There's a lot of online code beautifiers. If you're looking for a JSON beautifier precisely, you can try here: http://www.curiousconcept.com/jsonformatter/

Alternatively, there exists a list of other code formatters here: http://en.wikipedia.org/wiki/Prettyprint#Code_Beautifiers

-edit Sorry, I completely missed the first part, and it seems you want it done immediately after the output, but maybe this online tool would help you anyway.

+3  A: 

The JSON gem hosted on RubyForge might help you out. Just install the gem and the generator API looks pretty clear and clean and should support all the features you need.

Honza
The link to the generator API appears to be broken.
obvio171
+4  A: 

I looked into doing this and decided that I didn't really need my app to support pretty-printing of JSON output.

Instead, I installed the JSONView Firefox addon. The addon is great - it detects "application/json" content and presents it in an indented and colorized display that you can collapse and expand.

casey
A: 

Not sure where you're looking at it, but in webkit's console it creates a nice tree out of any JSON logged or requested.

rpflo
+13  A: 

Use the pretty_generate() function, built into later versions of JSON. Example:

require 'json'
my_json = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_json)

Which gets you...

{
  "array": [
    1,
    2,
    3,
    {
      "sample": "hash"
    }
  ],
  "foo": "bar"
}
jpatokal