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!
JSON Pretty Print helps Pretty JSON data and Print JSON data. It's very simple and easy way to prettify JSON and pretty print JSON. This is the # 1 tool to JSON Prettify. Know more about JSON. How to Create JSON File? What is JSON? JSON Example with all data types including JSON Array.
A problem with using JSON.pretty_generate is that JSON schema validators will no longer be happy with your datetime strings. You can fix those in your config/initializers/rabl_config.rb with:
Use the pretty_generate () function, built into later versions of JSON. For example: Show activity on this post. The <pre> tag in HTML, used with JSON.pretty_generate, will render the JSON pretty in your view. I was so happy when my illustrious boss showed me this: Show activity on this post.
JSON Pretty Print is very unique tool for prettify json and pretty print JSON data in color. JSON Pretty Print support URL linking for sharing json. No. It's not required to save and share code. Please send us the details of the URL using Contact US.
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"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With