jq: Filters and Paths
Almost every DevOps tool speaks JSON: kubectl get -o json, aws … --output json, docker inspect, terraform show -json, GitHub's API. jq is how shell scripts read it. The JSON course's jq lesson introduces the
basics on a small product list; this section uses the kind of nested, slightly messy data that real tools return,
and goes as far as you need for scripts.
All sessions here use jq 1.7.
The data
kubectl get pods -o json returns a List with an items array. A trimmed-down version (real output has many more
fields) is enough to practise on. Each session below starts by writing it to pods.json:
{
"kind": "List",
"items": [
{"metadata": {"name": "api-7d9f", "namespace": "shop", "labels": {"app": "api", "tier": "backend"}},
"spec": {"nodeName": "node-1", "containers": [{"name": "api", "image": "registry.example.com/api:1.4.2"}]},
"status": {"phase": "Running", "containerStatuses": [{"name": "api", "ready": true, "restartCount": 0}]}},
{"metadata": {"name": "api-x2kq", "namespace": "shop", "labels": {"app": "api", "tier": "backend"}},
"spec": {"nodeName": "node-2", "containers": [{"name": "api", "image": "registry.example.com/api:1.4.2"}]},
"status": {"phase": "Running", "containerStatuses": [{"name": "api", "ready": false, "restartCount": 7}]}},
{"metadata": {"name": "web-5c4b", "namespace": "shop", "labels": {"app": "web"}},
"spec": {"nodeName": "node-1", "containers": [{"name": "web", "image": "registry.example.com/web:2.0.0"},
{"name": "proxy", "image": "envoyproxy/envoy:v1.36.2"}]},
"status": {"phase": "Running", "containerStatuses": [{"name": "web", "ready": true, "restartCount": 1},
{"name": "proxy", "ready": true, "restartCount": 0}]}},
{"metadata": {"name": "migrate-q8z1", "namespace": "shop"},
"spec": {"containers": [{"name": "migrate", "image": "registry.example.com/api:1.4.2"}]},
"status": {"phase": "Pending"}}
]
}Paths: walking into the document
A filter starts from . (the input) and walks down with .key and [index]. .[] iterates over an array and
produces one output per element; pipes (|) feed each output into the next filter:
cat > pods.json <<'JSON'
{"kind": "List", "items": [
{"metadata": {"name": "api-7d9f", "namespace": "shop", "labels": {"app": "api", "tier": "backend"}}, "spec": {"nodeName": "node-1", "containers": [{"name": "api", "image": "registry.example.com/api:1.4.2"}]}, "status": {"phase": "Running", "containerStatuses": [{"name": "api", "ready": true, "restartCount": 0}]}},
{"metadata": {"name": "api-x2kq", "namespace": "shop", "labels": {"app": "api", "tier": "backend"}}, "spec": {"nodeName": "node-2", "containers": [{"name": "api", "image": "registry.example.com/api:1.4.2"}]}, "status": {"phase": "Running", "containerStatuses": [{"name": "api", "ready": false, "restartCount": 7}]}},
{"metadata": {"name": "web-5c4b", "namespace": "shop", "labels": {"app": "web"}}, "spec": {"nodeName": "node-1", "containers": [{"name": "web", "image": "registry.example.com/web:2.0.0"}, {"name": "proxy", "image": "envoyproxy/envoy:v1.36.2"}]}, "status": {"phase": "Running", "containerStatuses": [{"name": "web", "ready": true, "restartCount": 1}, {"name": "proxy", "ready": true, "restartCount": 0}]}},
{"metadata": {"name": "migrate-q8z1", "namespace": "shop"}, "spec": {"containers": [{"name": "migrate", "image": "registry.example.com/api:1.4.2"}]}, "status": {"phase": "Pending"}}
]}
JSON
echo "--- .kind"; jq '.kind' pods.json
echo "--- -r removes the quotes"; jq -r '.kind' pods.json
echo "--- first pod's name"; jq -r '.items[0].metadata.name' pods.json
echo "--- last pod's phase"; jq -r '.items[-1].status.phase' pods.json
echo "--- every pod's name"; jq -r '.items[].metadata.name' pods.json
echo "--- every image (nested arrays)"; jq -r '.items[].spec.containers[].image' pods.json
echo "--- count"; jq '.items | length' pods.json--- .kind
"List"
--- -r removes the quotes
List
--- first pod's name
api-7d9f
--- last pod's phase
Pending
--- every pod's name
api-7d9f
api-x2kq
web-5c4b
migrate-q8z1
--- every image (nested arrays)
registry.example.com/api:1.4.2
registry.example.com/api:1.4.2
registry.example.com/web:2.0.0
envoyproxy/envoy:v1.36.2
registry.example.com/api:1.4.2
--- count
4
-r(raw output) prints strings without JSON quotes: what you want when the result goes into a shell variable.- Negative indexes count from the end;
.[2:4]slices. .items[].spec.containers[].imageiterates twice, so thewebpod contributes two lines.
Missing keys, null and ?
Real data is ragged: the migrate pod has no labels, no node and no container statuses. jq returns null for a
missing key instead of failing, which is convenient and dangerous:
cat > pods.json <<'JSON'
{"items": [
{"metadata": {"name": "api-7d9f", "labels": {"app": "api"}}, "spec": {"nodeName": "node-1"}},
{"metadata": {"name": "migrate-q8z1"}, "spec": {}}
]}
JSON
echo "--- missing keys are null"; jq -c '.items[] | [.metadata.name, .metadata.labels.app, .spec.nodeName]' pods.json
echo "--- default with //"; jq -r '.items[] | "\(.metadata.name) on \(.spec.nodeName // "unscheduled")"' pods.json
echo "--- iterating null fails"; jq -r '.items[].metadata.labels[]' pods.json; echo "status $?"
echo "--- ? suppresses the error"; jq -r '.items[].metadata.labels[]?' pods.json; echo "status $?"
echo "--- has() and keys"; jq -c '.items[] | [.metadata.name, (.metadata | has("labels")), (.metadata | keys)]' pods.json--- missing keys are null
["api-7d9f","api","node-1"]
["migrate-q8z1",null,null]
--- default with //
api-7d9f on node-1
migrate-q8z1 on unscheduled
--- iterating null fails
jq: error (at pods.json:4): Cannot iterate over null (null)
api
status 5
--- ? suppresses the error
api
status 0
--- has() and keys
["api-7d9f",true,["labels","name"]]
["migrate-q8z1",false,["name"]]
.a.bon a missingagivesnull, not an error. A typo in a key name therefore also givesnull; seejq -ein jq in Scripts for turning that into a failure.//is the alternative operator:x // ygivesywhenxisnullorfalse."\(expr)"is string interpolation, the easiest way to build a line of output..[]onnullis an error (status 5). jq printedapifor the first pod and then stopped; the error appears first only because jq buffers its normal output..[]?(and.key?) quietly produce nothing instead.keysreturns the keys sorted;keys_unsortedkeeps the document's order.
select: filtering
select(condition) passes its input through when the condition is true and drops it otherwise:
cat > pods.json <<'JSON'
{"items": [
{"metadata": {"name": "api-7d9f", "labels": {"app": "api"}}, "status": {"phase": "Running", "containerStatuses": [{"ready": true, "restartCount": 0}]}},
{"metadata": {"name": "api-x2kq", "labels": {"app": "api"}}, "status": {"phase": "Running", "containerStatuses": [{"ready": false, "restartCount": 7}]}},
{"metadata": {"name": "web-5c4b", "labels": {"app": "web"}}, "status": {"phase": "Running", "containerStatuses": [{"ready": true, "restartCount": 1}, {"ready": true, "restartCount": 0}]}},
{"metadata": {"name": "migrate-q8z1"}, "status": {"phase": "Pending"}}
]}
JSON
echo "--- not Running"; jq -r '.items[] | select(.status.phase != "Running") | .metadata.name' pods.json
echo "--- app=api"; jq -r '.items[] | select(.metadata.labels.app == "api") | .metadata.name' pods.json
echo "--- any container not ready"
jq -r '.items[] | select(any(.status.containerStatuses[]?; .ready == false)) | .metadata.name' pods.json
echo "--- restarted more than 3 times"
jq -r '.items[] | select([.status.containerStatuses[]?.restartCount] | add > 3) | .metadata.name' pods.json
echo "--- name starts with api-"
jq -r '.items[].metadata.name | select(startswith("api-"))' pods.json--- not Running
migrate-q8z1
--- app=api
api-7d9f
api-x2kq
--- any container not ready
api-x2kq
--- restarted more than 3 times
api-x2kq
--- name starts with api-
api-7d9f
api-x2kq
any(generator; condition) and all(generator; condition) test a condition over a stream. Wrapping a stream in
[ … ] collects it into an array, so you can apply add, length, max and friends to it.
Exploring an unknown document
When you meet a new API response, find out its shape before writing filters:
cat > instance.json <<'JSON'
{"Reservations": [{"Instances": [{"InstanceId": "i-0abc", "State": {"Name": "running"},
"Tags": [{"Key": "Name", "Value": "web-1"}, {"Key": "env", "Value": "prod"}]}]}]}
JSON
echo "--- every path to a scalar value"
jq -c 'paths(scalars)' instance.json
echo "--- find a key anywhere with .."
jq -c '.. | objects | select(has("State")) | .State' instance.json--- every path to a scalar value
["Reservations",0,"Instances",0,"InstanceId"]
["Reservations",0,"Instances",0,"State","Name"]
["Reservations",0,"Instances",0,"Tags",0,"Key"]
["Reservations",0,"Instances",0,"Tags",0,"Value"]
["Reservations",0,"Instances",0,"Tags",1,"Key"]
["Reservations",0,"Instances",0,"Tags",1,"Value"]
--- find a key anywhere with ..
{"Name":"running"}
paths(scalars) lists the route to every leaf value, which you can turn directly into a filter. .. recurses into
every value of the document; combined with objects and select it finds a key wherever it is nested.
Test yourself
What does jq -r '.items[].metadata.name' output for a list of 4 pods?
- One JSON array with 4 strings
- 4 lines, one name each, without quotes
- The first name only
- An error, because
itemsis an array
What does .spec.nodeName // "unscheduled" evaluate to when nodeName is missing?
- null
- an error
- "unscheduled"
- an empty string
Why might .items[].metadata.labels[] fail on real data?
- Labels are always strings
- Some items have no labels, and iterating
nullis an error;.labels[]?avoids it - jq cannot iterate objects
- Because of the
-rflag