Published 2021-02-23.
Time to read: 1 minutes.
I've been using jq to format my JSON for years.
It is easy to format a JSON document, just pass it through jq without any options or arguments.
Notice, however, that a lot of vertical space is wasted using this formatting:
$ jq < blog/colors.json
{
"colors": [
{
"color": "black",
"hex": "#000",
"rgb": [
0,
0,
0
]
},
{
"color": "red",
"hex": "#f00",
"rgb": [
255,
0,
0
]
},
{
"color": "yellow",
"hex": "#ff0",
"rgb": [
255,
255,
0
]
},
{
"color": "green",
"hex": "#0f0",
"rgb": [
0,
255,
0
]
},
{
"color": "cyan",
"hex": "#0ff",
"rgb": [
0,
255,
255
]
},
{
"color": "blue",
"hex": "#00f",
"rgb": [
0,
0,
255
]
},
{
"color": "magenta",
"hex": "#f0f",
"rgb": [
255,
0,
255
]
},
{
"color": "white",
"hex": "#fff",
"rgb": [
255,
255,
255
]
}
]
}
After reading The Pretty JSON Revolution
I decided to try the program the article mentioned, oj.
oj is a Go program.
Here is how I compiled it on Ubuntu:
$ yes | sudo apt install golang-go $ go get github.com/ohler55/ojg $ go get github.com/ohler55/ojg/cmd/oj
By default, compiled go projects are placed in the ~/go/bin/ directory.
Here is how I added that directory to the PATH, and made an alias for invoking the program with the proper options for maximum prettiness:
$ echo "$HOME/go/bin/:$PATH" >> ~/.bashrc $ echo "alias pprint='oj -i 2 -s -p 80.3'" >> ~/.bash_aliases $ source ~/.bashrc
Pretty-printing the JSON in colors.json with oj is easy:
$ pprint colors.json { "colors": [ {"color": "black", "hex": "#000", "rgb": [0, 0, 0]}, {"color": "red", "hex": "#f00", "rgb": [255, 0, 0]}, {"color": "yellow", "hex": "#ff0", "rgb": [255, 255, 0]}, {"color": "green", "hex": "#0f0", "rgb": [0, 255, 0]}, {"color": "cyan", "hex": "#0ff", "rgb": [0, 255, 255]}, {"color": "blue", "hex": "#00f", "rgb": [0, 0, 255]}, {"color": "magenta", "hex": "#f0f", "rgb": [255, 0, 255]}, {"color": "white", "hex": "#fff", "rgb": [255, 255, 255]} ] }
I like it!
Give it to Mikey. He won't eat it. He hates everything!
I will continue to use jq for queries,
but I'll use oj for pretty-printing from now on.