Ruby JSON.pretty_generate ... is pretty unpretty

Posted by Amy on Stack Overflow See other posts from Stack Overflow or by Amy
Published on 2010-04-02T16:04:18Z Indexed on 2010/04/03 0:23 UTC
Read the original article Hit count: 833

Filed under:
|
|
|

I can't seem to get JSON.pretty_generate() to actually generate pretty output in Rails.

I'm using Rails 2.3.5 and it seems to automatically load the JSON gem. Awesome. While using script/console this does indeed produce JSON:

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

But this doesn't produce pretty output:

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

The only way I've found to generate it is to use irb and to load the Pure version:

require 'rubygems'
require 'json/pure'
some_data = {'foo' => 1, 'bar' => 20, 'cow' => [1, 2, 3, 4], 'moo' => {'dog' => 'woof', 'cat' => 'meow'}}
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}"

BUT, what I really want is Rails to produce this. Does anyone have any tips why I can't get the generator in Rails to work correctly?

Thanks!

Updated 5:20 PM PST: Corrected the output.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby