How to pretty print JSON from CLI

Software engineers frequently have to deal with JSON and inspect or manipulate it.

There are two easy ways of pretty-printing JSON from command-line to aid in visual inspection. The first requires no installation, and the second requires a minimal installation but also provides syntax highlighting and manipulation capabilities.

Method 1: Using Python - Nothing to Install

Optional: Add alias to .bashrc
alias json='python -mjson.tool'

Example:

$ echo '{"cool": { "story" : { "bro" : [1, 2, 3] } } }' | json
{
    "cool": {
        "story": {
            "bro": [
                1,
                2,
                3,
            ]
        }
    }
}

Reference: http://www.restlessprogrammer.com/2013/03/how-to-pretty-print-json-from-command.html

Method 2: Using JQ - Minimal Install

Mac install via Homebrew: brew install jq
Ubuntu install apt: sudo apt-get install jq

$ echo '{"cool": { "story" : { "bro" : [1, 2, 3] } } }' | jq .
{
    "cool": {
        "story": {
            "bro": [
                1,
                2,
                3
            ]
        }
    }
}

Reference: https://stedolan.github.io/jq/



blog comments powered by Disqus

Published

09 October 2017

Tags


Make a Donation