Notes to Self

Alex Sokolsky's Notes on Computers and Programming

jq

Repo

Manual

https://www.linode.com/docs/guides/using-jq-to-process-json-on-the-command-line/

Pretty print

Just pipe it

terraform show -json|jq

Or to pretty print file:

jq '.' menu.json

Filtering

To access a particular property within a JSON record, use the .field operator:

terraform show -json|jq '.values.root_module.child_modules'

If the filed has a reserved character, e.g. ‘.’, escape it using double quote:

kubectl get secret lacework -n lacework -o jsonpath='{.data}'|jq '."config.json"'

To view a specific entry within an array, specify the index of the item within the [] operator:

terraform show -json|jq '.values.root_module.child_modules[0]'

To access an array nested deeper within a JSON file, first use the field operator to extract the array object. Pipe the result to the [] operator:

jq '.values.root_module.child_modules[0].resources|.[].values.private_key_pem' tt1.json
null
null
null
null
null
"-----BEGIN RSA PRIVATE KEY-----\nMIIJK...\n-----END RSA PRIVATE KEY-----\n"

To get the last element of the array use index -1:

jq '.values.root_module.child_modules[0].resources[-1].values.private_key_pem' tt1.json

You can also “slice” the array to show only a portion of it: [first:last]. The first is inclusive, while the last is exclusive. E.g. to display the first two items of an array, use [0:2].

Sorting

Simple sort by key:

jq --sort-keys < foo.json

Extract container environment and sort it.

sudo docker inspect cc43cbfa4153|jq ".[0].Config.Env|sort[]"