Ruby JSON.pretty_generate … is pretty unpretty

▼魔方 西西 提交于 2019-12-21 03:20:13

问题


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!


回答1:


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"
  }
}



回答2:


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}"


来源:https://stackoverflow.com/questions/2567670/ruby-json-pretty-generate-is-pretty-unpretty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!