Skip to content
jq

jq

add or modify json key/value

let’s say you want to add "apitoken": "top-secret" within clodflare.

example cf.json test file:

{
  "cloudflare": {
    "TYPE": "CLOUDFLAREAPI",
    "accountid": "foobar"
  }
}

do this:

jq '.cloudflare.apitoken = "top-secret"' cf.json | sponge cf.json

with sponge the file will be written to disk and updated.

delete key/value from json file

assume you want to delete the apitoken field from cf.json, do this:

jq 'del(.cloudflare.apitoken)' cf.json | sponge cf.json

get multiple items

just comma separate what you want

bw list items --search zoho|jq '.[].login.username, .[].login.password'

format jq output

print multiple selections in one line

separated with -

jq -r '.[] | "\(.Name) - \(.Description)"' file.json

print columns

jq -r '.[] | [.Name, .Description] | @tsv' file.json

with headers and aligned columns:

jq -r '["Name", "Description"], (.[] | [.Name, .Description]) | @tsv' file.json | column -t -s $'\t'

filter (grep) json using jq

example: filter traefik json logs for a specific hostname (RequestAddr):

docker logs -f --tail=10 traefik |
  jq --unbuffered -c --arg domain "example.com" \
    'select((.RequestAddr? // "") | contains($domain))'

--unbuffered is useful for live logs, otherwise omit that. remove -c to see the output pretty-printed

search for multiple matches

tail -F access.log |
  jq --unbuffered -c \
    --arg d1 "example.com" \
    --arg d2 "example.org" \
    'select((.RequestAddr? // "") | (contains($d1) or contains($d2)))'

equal search

jq -c --arg d1 "example.com" --arg d2 "example.org" \
  'select(.RequestAddr? == $d1 or .RequestAddr? == $d2)' \
  access.log

filter uptime kuma cli tags

jq -r '
  .[]
  | select(any(.tags[]?; .name == "backups"))
  | [.id, .name]
  | @tsv
' input.json

get only the id (or any other field):

jq -r '.[] | select(any(.tags[]?; .name == "backups")) | .id' input.json

get raw output

… instead of JSON strings for example

-r               output raw strings, not JSON texts;
jq -r '.[].login.username, .[].login.password'

get the first element

jq .[0] file.json

merge multiple json files

for example: fitbit export, separated by day but same format otherwise. I wanted one file out of 4 years of data:

jq -s . heart_rate*.json > ../heart_rate.json

or just use flatten like this:

jq -c --slurp 'flatten' steps-*.json > ../steps.json

pretty print json

your-json | jq
jq < file.json

reformat json file (formatting, prettier)

jq < ~/downloads/data.json | sponge ~/downloads/data.json

you might not need jq

curl -sS https://abc.json | python -m json.tool