Pretty Printing JSON on the Command Line with Ruby

Featured image for sharing metadata for article

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:

Note: You can use Kernel.jj as a shorter way to pretty-print an object as JSON.

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.