Skip to content

jq

Install

  • Arch: sudo pacman -S jq
  • Debian: sudo apt install jq

Usage

Parse / extract data

Suppress quotes from output (raw output):

jq -r '.ip_address' < ~/projects/json/aardwolf.json

List all sha:

jq '.[] | { sha }' < $JSON

List all keys:

https://michaelheap.com/extract-keys-using-jq/

jq '.paths | to_entries[].key' < ~/projects/work/greenhost/api-help.json

List all extension data:

export JSON=~/.mozilla/firefox/default/addons.json
jq '.addons[].id' < $JSON
jq '.addons[] | { name: .name, id: .id, type: .type }' < $JSON


grep 'extensions.xpiState' ~/.mozilla/firefox/default/prefs.js | \
  sed 's/^user_pref("extensions.xpiState", "//' | sed 's/");$//' | sed 's/\\//g' | jq .

Special characters (i.e. dash) in keys:

https://github.com/stedolan/jq/issues/1224

echo '{"p-name": "Dr Nic"}' | jq -r '.["p-name"]'
curl -s --netrc echo.oas.varac.net -L | jq '.request.headers["x-real-ip"]'

Filter objects based on the contents of a value:

jq '.letsencrypt.Certificates[].domain | select(.main | contains("www"))' < letsencrypt/acme.json
ip -j route list | jq '.[] | select(.protocol=="unspec")'

Filter all results which have not the status of IGNORED or PASSED:

jq '.results[] | select([.status] | inside(["IGNORED", "PASSED"]) | not)'

Remove key containng a value:

jq '.| del(.letsencrypt.Certificates[] | select(.domain.main == "www.moewe-altonah.de"))' letsencrypt/acme.json | \
  sponge letsencrypt/acme.json`

Modify data

jq '.Statement[0].Resource = ["arn:aws:s3:::restic-zancas"]' \
  ~/projects/cloud/storage/minio/policy.readwrite.json

Examples

jq with prometheus

Alert count:

jq '.data.alerts | length' < ~/projects/monitoring/prometheus/example-alerts.json

Successful ?

jq 'contains({status: "success"})' < example-alerts.json

Filter out the none serverity alerts:

jq -c '.data.alerts[] | select(.labels.severity | contains("none") | not)' < example-alerts.json | jq .

and count them:

jq -c '[.data.alerts[] | select(.labels.severity | contains("none") | not )] | length' < example-alerts.json

ndjson

jq can parse ndjson

jq . < /tmp/renovate-log.ndjson

Compact lines (but wrap):

jq --compact-output . < /tmp/renovate-log.ndjson