Pretty Printing JSON with Ruby

Featured image for sharing metadata for article

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's profile image 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.

#blogumentation #ruby #json #pretty-print.

This post was filed under articles.

This post is part of the series pretty-print-json.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

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

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.