Using jq to work with JSON
I often see processing of JSON on the shell through tools like grep
and awk
.
Sure, this works but usually it depends on the output having only one item per line and not having the keywords you are grep'ing for in other places.
So I was very delighted to learn that there is a better way through the commandline tool jq.
With jq
you can filter, slice and alter JSON.
And you get some highlighting of the output which makes it nicer to read than plain text!
Here are two small examples I tried out today to process output from opsi-admin
:
opsi-admin -d method host_getHashes | jq '.[] | .id + ": " + .lastSeen'
This will list all your clients along with the time they have been last seen. The output on my test machine looks like this
...snip... "vtest16r.uib.local: 2013-09-08 21:28:50" "vtest18-w2k-r.uib.local: 2008-05-24 17:58:35" "zedach.uib.local: 2011-01-19 15:47:18" ...snip...
And to see what installation status the products on your clients have you can use this snippet:
opsi-admin -d method productOnClient_getHashes | jq '.[] | "On " + .clientId + " the product " + .productId + " is " + .installationStatus'
Again with some example output:
...snip... "On pcbon4.uib.local the product xnview is installed" "On fscnoteb1.uib.local the product xpknife is unknown" "On vtest16r.uib.local the product xpknife is installed" "On fscnoteb1.uib.local the product yed is installed" "On hpnoteb1.uib.local the product yed is installed" "On pcbon4.uib.local the product yed is installed" ...snip...
Creating new JSON data is also possible:
opsi-admin -d method productOnClient_getHashes | jq '.[] | {hostId: .clientId, productId: .productId, status: .installationStatus}'
This return something like the following (look ahead: no JSON list but multiple standalone dictionaries instead):
...snip... { "hostId": "vmex12w10x64c.uib.local", "productId": "winscp", "status": "installed" } { "hostId": "vmex12w10x86.uib.local", "productId": "winscp", "status": "installed" } ...snip...
If you want to know more I'd suggest to start with the documentation. If you do not want to install anything on your machine there even is an online version to play with.