Pretty Printing JSON with Ruby
If you're debugging your Ruby code, you may be used to printing out variables to the console to see what they contain, such as:
hash = {
abc: [
1
]
}
# print the variable
puts hash
# print the internal representation of the variable
p hash
# pretty-print using the `pp` gem
require 'pp'
pp hash
#
puts JSON.pretty_generate(hash)
Which would give you the following representations:
{:abc=>[1]}
{:abc=>[1]}
{:abc=>[1]}
{
"abc": [
1
]
}
However, you may not be aware of Kernel.jj
which is a nice wrapper around the latter option:
hash = {
abc: [
1
]
}
jj hash
And generates a nicely pretty-printed JSON representation of our i.e. Hash:
{
"abc": [
1
]
}
This makes debugging nicer, as then we can see nice JSON representations.