2018-06-18-pretty-printing-json-ruby-cli.md 1.95 KB
Newer Older
1 2 3
---
title: Pretty Printing JSON on the Command Line with Ruby
description: Using Ruby's JSON module to pretty print JSON objects from the command line.
4 5 6 7 8 9
categories:
- blogumentation
tags:
- blogumentation
- ruby
- json
10
- pretty-print
11
date: 2018-06-18T19:13:49+01:00
12 13
license_prose: CC-BY-NC-SA-4.0
license_code: Apache-2.0
14
slug: pretty-printing-json-ruby-cli
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
---
This is a follow up to the popular post [Pretty Printing JSON on the Command Line with Python][pp-python-json] that uses Ruby to perform the pretty-printing.

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

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

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


```bash
$ 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:

48
<asciinema-player src="/casts/pretty-printing-json-ruby-cli.json"></asciinema-player>
49

50 51
Note: You can use [`Kernel.jj` as a shorter way to pretty-print an object as JSON]({{< ref 2019-03-29-pretty-printing-json-ruby >}}).

52
[so-stdin]: https://stackoverflow.com/questions/273262/best-practices-with-stdin-in-ruby
53
[pp-python-json]: {{< ref 2017-06-05-pretty-printing-json-cli >}}