snippetrubyrailsCritical
How to "pretty" format JSON output
Viewed 0 times
howoutputprettyformatjson
Problem
I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted.
Right now, I call
Is there way to configure to make my JSON "pretty" or nicely formatted in Ruby on Rails?
Right now, I call
to_json and my JSON is all on one line. At times this can be difficult to see if there is a problem in the JSON output stream.Is there way to configure to make my JSON "pretty" or nicely formatted in Ruby on Rails?
Solution
Use the
Which gets you:
pretty_generate() function, built into later versions of JSON. For example:require 'json'
my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_object)Which gets you:
{
"array": [
1,
2,
3,
{
"sample": "hash"
}
],
"foo": "bar"
}Code Snippets
require 'json'
my_object = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_object){
"array": [
1,
2,
3,
{
"sample": "hash"
}
],
"foo": "bar"
}Context
Stack Overflow Q#86653, score: 1184
Revisions (0)
No revisions yet.