Drill: jq Recipes for JSON Processing¶
Goal¶
Use jq to select, filter, map, and transform JSON output from APIs and Kubernetes commands.
Setup¶
- Install jq (
apt install jqoryum install jq) - JSON data to process (API responses, kubectl output, config files)
Commands¶
Pretty-print JSON:
Extract a field:
Extract from an array:
Select/filter array elements:
echo '[{"name":"a","status":"running"},{"name":"b","status":"failed"}]' | jq '.[] | select(.status == "failed")'
Map over an array to extract fields:
Use with kubectl:
Filter pods by status:
Count items:
Construct new JSON:
Handle null values:
Raw string output (no quotes):
Sort and group:
kubectl get pods -o json | jq '[.items[] | .status.phase] | group_by(.) | map({state: .[0], count: length})'
What to Look For¶
.[]iterates over array elements;.fieldaccesses object fieldsselect()filters;map()transforms;group_by()aggregates-rgives raw strings without JSON quoting (useful for shell variables)//provides a default value when a field is null
Common Mistakes¶
- Forgetting
-rand getting quoted strings in shell variables - Using
.[]on an object (iterates values) when you meant.keys[] - Not wrapping filter output in
[]when you need the result as an array - Forgetting that jq expressions are single-quoted to prevent shell interpolation
Cleanup¶
No cleanup needed. jq processes stdin/files without modification.