Pretty Printing JSON on the Command Line with Ruby

This is a follow up to the popular post Pretty Printing JSON on the Command Line with Python that uses Ruby to perform the pretty-printing.

Given the following minified JSON file that we want to be able to inspect:


Let's use the following pipeline to output it, taking advantage of ARGF, which is a file descriptor that points to stdin:

$ cat file.json | ruby -rjson -e 'puts JSON.pretty_generate(JSON.parse('
#                                                                      ^ read from a file
#                                                           ^ parse a JSON string to a Ruby Hash
#                                      ^ pretty print (
#                                 ^ output to stdout
#                        ^ require the Ruby JSON module
# ^ useless use of cat, use recommended pipeline(s) below instead:
$ ruby -rjson -e 'puts JSON.pretty_generate(JSON.parse(' file.json
$ ruby -rjson -e 'puts JSON.pretty_generate(JSON.parse(' < file.json
    "key": [
    "key2": "value"

To see this article in action, check out the asciicast:


Written by Jamie Tanna on 18 June 2018.

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 Apache License 2.0.