How to use JC to convert the output of a command to JSON format

How to use JC to convert the output of a command to JSON format

5/5 - (33 votes)

If you’re coding or working on the command line and need to retrieve the output of a command-line tool or files in XML format and export it to JSON or dictionaries for Python, I have just what you need.

It’s called JC and it’s available as a command-line tool or a Python library. You can redirect the output of a command to JC using a pipe like this, specifying the dig parser (there are many parsers available):

dig example.com | jc --dig

And get output like this:

[{"id":38052,"opcode":"QUERY","status":"NOERROR","flags":["qr","rd","ra"],

"query_num":1,"answer_num":1,"authority_num":0,"additional_num":1,

"opt_pseudosection":{"edns":{"version":0,"flags":[],"udp":4096}},"question":

{"name":"example.com.","class":"IN","type":"A"},"answer":[{"name":

"example.com.","class":"IN","type":"A","ttl":39049,"data":"93.184.216.34"}],

"query_time":49,"server":"2600:1700:bab0:d40::1#53(2600:1700:bab0:d40::1)",

"when":"Fri Apr 16 16:09:00 PDT 2021","rcvd":56,"when_epoch":1618614540,

"when_epoch_utc":null}]

If you’re feeling adventurous, you can even chain it with the jq command like this to retrieve a specific piece of information:

dig example.com | jc --dig | jq -r '.[].answer[].data'

This is very useful for retrieving data in your Python scripts or outputting this data in JSON to import it elsewhere. With this, you can parse commands like crontab, ls, free, mount, hosts, ping, ps, systemctl, traceroute, or file formats like CSV, XML, YAML, etc.

There’s even an online demo if you want to try it out before installing it.

If you’re interested, the Github repository is here.