ubuntu, updated

jq cheat sheet

Read, filter and reshape JSON on the command line: pretty-print, pick fields, filter arrays, and turn API output into lists and CSV.

What it is

APIs, cloud CLIs, Docker and many tools speak JSON. jq reads JSON and lets you pick and reshape the parts you need.

sudo apt install jq

All examples use this input (servers.json):

{
  "env": "prod",
  "servers": [
    { "name": "web01", "ip": "10.0.0.11", "role": "web", "cpu": 4, "tags": ["nginx"] },
    { "name": "web02", "ip": "10.0.0.12", "role": "web", "cpu": 4, "tags": ["nginx"] },
    { "name": "db01",  "ip": "10.0.0.21", "role": "db",  "cpu": 8, "tags": ["postgres"] }
  ]
}

Picking values

WhatCommandResult
Pretty-printjq . servers.jsonformatted, colored JSON
One fieldjq .env servers.json"prod"
Without quotes (raw)jq -r .env servers.jsonprod
One array elementjq '.servers[0]' servers.jsonfirst server
Every elementjq '.servers[]' servers.jsoneach server
One field of every elementjq -r '.servers[].name' servers.jsonweb01 web02 db01
Countjq '.servers | length' servers.json3
List keysjq 'keys' servers.json["env","servers"]

-r (raw output) is what you want almost always when the result goes into a script or another command.

Filtering

WhatCommand
Where a field equals a valuejq '.servers[] | select(.role == "db")'
Number comparisonjq '.servers[] | select(.cpu >= 8)'
Text containsjq '.servers[] | select(.name | contains("web"))'
Array containsjq '.servers[] | select(.tags | index("nginx"))'
Field exists / is not nulljq '.servers[] | select(.ip != null)'
Filter, then pick one fieldjq -r '.servers[] | select(.role == "web") | .ip'

Reshaping

WhatCommand
New object with chosen fieldsjq '.servers[] | {name, ip}'
Rename fieldsjq '.servers[] | {host: .name, addr: .ip}'
Keep it as an arrayjq '[.servers[] | {name, ip}]'
Two fields as textjq -r '.servers[] | "\(.name) \(.ip)"'
Tab-separatedjq -r '.servers[] | [.name, .ip] | @tsv'
CSVjq -r '.servers[] | [.name, .ip, .role] | @csv'
Sortjq '.servers | sort_by(.cpu)'
Sumjq '[.servers[].cpu] | add'
Group and countjq '.servers | group_by(.role) | map({role: .[0].role, count: length})'

Changing JSON

jq '.env = "staging"' servers.json                    # set a value
jq 'del(.servers[0])' servers.json                     # delete an element
jq --arg ip "10.0.0.99" '.servers[0].ip = $ip' servers.json   # use a shell value safely
jq '.env = "staging"' servers.json > tmp && mv tmp servers.json   # "in place"

jq never changes the file itself. Write to a temp file and move it.

Real-world examples

# Public IP and location
curl -s https://ipinfo.io | jq -r '.ip, .city'

# Names and states of all Docker containers
docker inspect $(docker ps -aq) | jq -r '.[] | "\(.Name) \(.State.Status)"'

# IPs of all interfaces (ip can output JSON!)
ip -j addr | jq -r '.[] | .ifname + " " + (.addr_info[]? | select(.family=="inet") | .local)'

# Disks as JSON
lsblk -J | jq -r '.blockdevices[] | "\(.name) \(.size)"'

# Loop over JSON results in Bash
jq -r '.servers[].ip' servers.json | while read -r IP; do ping -c1 -W1 "$IP"; done

Many tools have a JSON output option (ip -j, lsblk -J, docker inspect, systemctl --output=json, ss does not). Combined with jq that is much more robust than cutting text with awk.

§ home
~/knubertus/home/
1,1 Top