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.jsonwith 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.jsonget 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.jsonprint columns
jq -r '.[] | [.Name, .Description] | @tsv' file.jsonwith 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.logfilter uptime kuma cli tags
jq -r '
.[]
| select(any(.tags[]?; .name == "backups"))
| [.id, .name]
| @tsv
' input.jsonget only the id (or any other field):
jq -r '.[] | select(any(.tags[]?; .name == "backups")) | .id' input.jsonget 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.jsonmerge 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.jsonor just use flatten like this:
jq -c --slurp 'flatten' steps-*.json > ../steps.jsonpretty print json
your-json | jq
jq < file.jsonreformat json file (formatting, prettier)
jq < ~/downloads/data.json | sponge ~/downloads/data.jsonyou might not need jq
curl -sS https://abc.json | python -m json.tool