jq: Transforming Data
Reading values is half of jq. The other half is reshaping: building new objects, grouping and counting, turning arrays of key/value pairs into maps, producing CSV for a spreadsheet or a table for a terminal. This lesson covers the transformations that come up in operations work.
Building objects and arrays
{…} builds an object and […] collects outputs into an array. map(f) is shorthand for [.[] | f]:
cat > pods.json <<'JSON'
{"items": [
{"metadata": {"name": "api-7d9f", "labels": {"app": "api"}}, "spec": {"nodeName": "node-1", "containers": [{"image": "registry.example.com/api:1.4.2"}]}, "status": {"phase": "Running", "containerStatuses": [{"restartCount": 0}]}},
{"metadata": {"name": "api-x2kq", "labels": {"app": "api"}}, "spec": {"nodeName": "node-2", "containers": [{"image": "registry.example.com/api:1.4.2"}]}, "status": {"phase": "Running", "containerStatuses": [{"restartCount": 7}]}},
{"metadata": {"name": "web-5c4b", "labels": {"app": "web"}}, "spec": {"nodeName": "node-1", "containers": [{"image": "registry.example.com/web:2.0.0"}, {"image": "envoyproxy/envoy:v1.36.2"}]}, "status": {"phase": "Running", "containerStatuses": [{"restartCount": 1}, {"restartCount": 0}]}},
{"metadata": {"name": "migrate-q8z1"}, "spec": {"containers": [{"image": "registry.example.com/api:1.4.2"}]}, "status": {"phase": "Pending"}}
]}
JSON
echo "--- one summary object per pod"
jq -c '.items[] | {name: .metadata.name, node: (.spec.nodeName // "-"), restarts: ([.status.containerStatuses[]?.restartCount] | add // 0)}' pods.json
echo "--- the same, as one array, with map"
jq -c '.items | map({name: .metadata.name, phase: .status.phase})' pods.json
echo "--- unique images"
jq -r '[.items[].spec.containers[].image] | unique[]' pods.json
echo "--- sorted by restarts, highest first"
jq -r '.items | map({n: .metadata.name, r: ([.status.containerStatuses[]?.restartCount] | add // 0)}) | sort_by(-.r)[] | "\(.r)\t\(.n)"' pods.json--- one summary object per pod
{"name":"api-7d9f","node":"node-1","restarts":0}
{"name":"api-x2kq","node":"node-2","restarts":7}
{"name":"web-5c4b","node":"node-1","restarts":1}
{"name":"migrate-q8z1","node":"-","restarts":0}
--- the same, as one array, with map
[{"name":"api-7d9f","phase":"Running"},{"name":"api-x2kq","phase":"Running"},{"name":"web-5c4b","phase":"Running"},{"name":"migrate-q8z1","phase":"Pending"}]
--- unique images
envoyproxy/envoy:v1.36.2
registry.example.com/api:1.4.2
registry.example.com/web:2.0.0
--- sorted by restarts, highest first
7 api-x2kq
1 web-5c4b
0 api-7d9f
0 migrate-q8z1
Grouping and counting
group_by(f) sorts an array by f and splits it into arrays of equal f. Combined with map it answers "how many
per X" questions:
cat > pods.json <<'JSON'
{"items": [
{"metadata": {"name": "api-7d9f"}, "spec": {"nodeName": "node-1"}, "status": {"phase": "Running"}},
{"metadata": {"name": "api-x2kq"}, "spec": {"nodeName": "node-2"}, "status": {"phase": "Running"}},
{"metadata": {"name": "web-5c4b"}, "spec": {"nodeName": "node-1"}, "status": {"phase": "Running"}},
{"metadata": {"name": "migrate-q8z1"}, "spec": {}, "status": {"phase": "Pending"}},
{"metadata": {"name": "backup-j7"}, "spec": {"nodeName": "node-2"}, "status": {"phase": "Failed"}}
]}
JSON
echo "--- pods per phase"
jq -c '.items | group_by(.status.phase) | map({phase: .[0].status.phase, count: length})' pods.json
echo "--- names per node, as a map"
jq -c '.items | map(select(.spec.nodeName)) | group_by(.spec.nodeName) | map({key: .[0].spec.nodeName, value: map(.metadata.name)}) | from_entries' pods.json
echo "--- the same count with reduce"
jq -c 'reduce .items[] as $p ({}; .[$p.status.phase] += 1)' pods.json--- pods per phase
[{"phase":"Failed","count":1},{"phase":"Pending","count":1},{"phase":"Running","count":3}]
--- names per node, as a map
{"node-1":["api-7d9f","web-5c4b"],"node-2":["api-x2kq","backup-j7"]}
--- the same count with reduce
{"Running":3,"Pending":1,"Failed":1}
reduce STREAM as $x (INIT; UPDATE) folds a stream into one value; here it builds a counter object. .[key] += 1
works even when the key is missing, because null + 1 is 1 in jq.
Objects as data: to_entries, from_entries, with_entries
Labels, tags and environment maps are objects whose keys are data. to_entries turns
{"app": "api"} into [{"key": "app", "value": "api"}] so you can filter and transform keys like values;
from_entries turns it back. AWS uses the opposite representation, a list of {"Key": …, "Value": …} tags, which
from_entries also accepts:
cat > labels.json <<'JSON'
{"app": "api", "tier": "backend", "team": "core", "kubernetes.io/managed-by": "helm"}
JSON
echo "--- key=value lines"
jq -r 'to_entries[] | "\(.key)=\(.value)"' labels.json
echo "--- drop system labels (keys containing a /)"
jq -c 'with_entries(select(.key | contains("/") | not))' labels.json
echo "--- prefix every key"
jq -c 'with_entries(.key |= "label_" + .)' labels.json
echo "--- AWS-style tags to a map"
echo '{"Tags": [{"Key": "Name", "Value": "web-1"}, {"Key": "env", "Value": "prod"}]}' | jq -c '.Tags | from_entries'--- key=value lines
app=api
tier=backend
team=core
kubernetes.io/managed-by=helm
--- drop system labels (keys containing a /)
{"app":"api","tier":"backend","team":"core"}
--- prefix every key
{"label_app":"api","label_tier":"backend","label_team":"core","label_kubernetes.io/managed-by":"helm"}
--- AWS-style tags to a map
{"Name":"web-1","env":"prod"}
Updating in place: |= and del
path |= f updates the value at a path and keeps the rest of the document; del(path) removes it. This is how you
patch a JSON config without rewriting it by hand:
cat > config.json <<'JSON'
{"service": "api", "replicas": 2, "image": {"repo": "registry.example.com/api", "tag": "1.4.2"},
"env": {"LOG_LEVEL": "info", "DEBUG_TOKEN": "x-123"}}
JSON
jq -c '.image.tag = "1.5.0" | .replicas |= . * 2 | del(.env.DEBUG_TOKEN) | .env.REGION = "eu-west-1"' config.json{"service":"api","replicas":4,"image":{"repo":"registry.example.com/api","tag":"1.5.0"},"env":{"LOG_LEVEL":"info","REGION":"eu-west-1"}}
= sets a value computed from the original input (.image.tag = .service would use the top-level .service),
while |= passes the current value at that path to the right-hand side (. * 2 is the old replicas times two).
Output formats: @csv, @tsv, @sh, @base64
The @format filters turn values into text for other tools:
cat > pods.json <<'JSON'
[{"name": "api-7d9f", "node": "node-1", "restarts": 0},
{"name": "web, legacy", "node": "node-2", "restarts": 3}]
JSON
echo "--- CSV (quotes strings, escapes commas)"
jq -r '.[] | [.name, .node, .restarts] | @csv' pods.json
echo "--- TSV, with tab stops expanded for the terminal"
{ printf 'NAME\tNODE\tRESTARTS\n'; jq -r '.[] | [.name, .node, .restarts] | @tsv' pods.json; } | expand -t 14
echo "--- shell-quoted, safe to eval"
jq -r '.[] | @sh "kubectl delete pod \(.name)"' pods.json
echo "--- base64 (Kubernetes Secret values)"
jq -rn '"s3cr3t" | @base64'--- CSV (quotes strings, escapes commas)
"api-7d9f","node-1",0
"web, legacy","node-2",3
--- TSV, with tab stops expanded for the terminal
NAME NODE RESTARTS
api-7d9f node-1 0
web, legacy node-2 3
--- shell-quoted, safe to eval
kubectl delete pod 'api-7d9f'
kubectl delete pod 'web, legacy'
--- base64 (Kubernetes Secret values)
czNjcjN0
@sh quotes each interpolated value for the shell, so a name with spaces or quotes cannot inject commands. Better
still, avoid eval entirely and read the values into an array (see jq in Scripts).
Test yourself
What does group_by(.status.phase) | map({phase: .[0].status.phase, count: length}) produce?
- One object per pod
- One object per distinct phase with the number of pods in it
- The phases sorted alphabetically, without counts
- An error, because group_by needs a number
Which filter turns {"app": "api"} into [{"key": "app", "value": "api"}]?
- keys
- to_entries
- from_entries
- paths
What is the difference between .replicas = . * 2 and .replicas |= . * 2?
- None
- With
=,.is the whole input document; with|=,.is the current value of.replicas |=deletes the key=only works on strings