Ruby JSON.pretty_generate ...非常有价值 [英] Ruby JSON.pretty_generate ... is pretty unpretty
问题描述
我似乎无法获得 JSON.pretty_generate()
,以便在Rails中真正生成漂亮的输出。
I can't seem to get JSON.pretty_generate()
to actually generate pretty output in Rails.
我正在使用Rails 2.3.5,它似乎自动加载JSON宝石。真棒。在使用脚本/控制台
时,确实会产生JSON:
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}"
我发现生成它的唯一方法是使用 irb
并加载Pure版本:
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}"
但是,我真正想要的是Rails制作这个。有没有人有任何提示,为什么我不能让Rails中的生成器正常工作?
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!
推荐答案
为了生成漂亮的JSON输出,看起来你只是缺少 puts
调用。
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'}}
只调用 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"
}
}
这篇关于Ruby JSON.pretty_generate ...非常有价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!