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.

Written by Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

Categories:

Tags:

Other posts you may be interested in:

Interactions with this post

This post has had 0 WebMention interactions, as of Tue, 23 Apr 2019 22:18:12 +0100.

Have you written a response to this post? Let me know the URL: