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:
Note: You can use Kernel.jj
as a shorter way to pretty-print an object as JSON.