Ruby JSON.pretty_generate ... is pretty unpretty Ruby JSON.pretty_generate ... is pretty unpretty json json

Ruby JSON.pretty_generate ... is pretty unpretty


To generate pretty JSON output it appears that you're only missing a puts call.

The data:

some_data = {'foo' => 1, 'bar' => 20, 'cow' => [1, 2, 3, 4], 'moo' => {'dog' => 'woof', 'cat' => 'meow'}}

Calling only JSON.pretty_generate:

> JSON.pretty_generate some_data => "{\n  \"foo\": 1,\n  \"bar\": 20,\n  \"cow\": [\n    1,\n    2,\n    3,\n    4\n  ],\n  \"moo\": {\n    \"dog\": \"woof\",\n    \"cat\": \"meow\"\n  }\n}"

Adding a puts into the mix:

> puts JSON.pretty_generate some_data{  "foo": 1,  "bar": 20,  "cow": [    1,    2,    3,    4  ],  "moo": {    "dog": "woof",    "cat": "meow"  }}


I use Rails 2.3.8 and installed the JSON gem (gem install json). JSON.pretty_generate now does nicely in script/console:

>> some_data = {'foo' => 1, 'bar' => 20, 'cow' => [1, 2, 3, 4], 'moo' => {'dog' => 'woof', 'cat' => 'meow'}}=> {"cow"=>[1, 2, 3, 4], "moo"=>{"cat"=>"meow", "dog"=>"woof"}, "foo"=>1, "bar"=>20}>> JSON.pretty_generate(some_data)=> "{\n  \"cow\": [\n    1,\n    2,\n    3,\n    4\n  ],\n  \"moo\": {\n    \"cat\": \"meow\",\n    \"dog\": \"woof\"\n  },\n  \"foo\": 1,\n  \"bar\": 20\n}"