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:

{"key":[123,456],"key2":"value"}

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(ARGF.read))'
#                                                                      ^ read from a file
#                                                           ^ parse a JSON string to a Ruby Hash
#                                      ^ pretty print (https://stackoverflow.com/a/1823885)
#                                 ^ 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(ARGF.read))' file.json
$ ruby -rjson -e 'puts JSON.pretty_generate(JSON.parse(ARGF.read))' < file.json
{
    "key": [
        123,
        456
    ],
    "key2": "value"
}

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

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 Sun, 24 Mar 2019 13:54:26 +0000.

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