JSON output from CLI commands
Posted 25 April 2020 in cli, json, and programmingI write automation software at work. Most of the time I have to write custom parsers for the output of CLI commands so the automation software knows how to proceed. "Is the hardware mode set correctly? Okay, set the hardware mode." That kind of thing. Typically, every time I need to add a new feature I have to introduce a new command, and that means writing a new parser. I feel lucky if the command supports some kind of structured output, like writing the output with quotes around values, or outputting values and keys on separate lines.
But recently while introducing a new tool I discovered that it supports JSON output. My first thought was "What, did the vendor write a firmware updater in Node?", but my second thought was that this was exactly what I had been looking for. It turns out that even some standard Linux commands support JSON output.
Behold, sample output from lsblk
!
NAME HCTL TYPE VENDOR MODEL REV TRAN
sda 2:0:0:0 disk ATA ST9160823ASG D sata
Notice how the "REV" column header is right-aligned. You might ask "Why?", but down that road lies madness.
And here's the JSON version:
{
"blockdevices": [
{
"name": "sda",
"hctl": "2:0:0:0",
"type": "disk",
"vendor": "ATA ",
"model": "ST9160823ASG ",
"rev": "D ",
"tran": "sata"
},
]
}
It's like a breath of fresh air. I have no idea why the values are padded with whitespace but it's easy to strip that out.
Listen, if you're writing or maintaining a CLI utility then please add JSON-formatted output; I may need to parse its output one day. Thanks!