Selecting and transforming JSON with jq
- Version
- unversioned
- Review
- Draft
Summary#
jq runs a filter on JSON from a file or standard input. A filter can emit a field, keep matching items from an array, or build new objects from selected values.
Syntax#
jq '.owner' job.json
jq -r '.name' job.json
jq -c '.[] | select(.ready == true) | {job: .name}' jobs.json
jq -e '.ready' job.json
.[] emits each array element. The pipe inside the filter sends each element to select(...), and {job: .name} turns each match into a new object. -c puts each JSON result on one line. -r prints string results as plain text without JSON quotes.
With -e, the last result determines the status after a successful evaluation. The status is 1 for false or null, 0 for any other result and 4 when the filter emits nothing.
Example#
This input contains two jobs. One is ready, neither has an owner and neither is a release job.
(
set -eu
jobs='[{"name":"lint","ready":true},{"name":"deploy","ready":false}]'
printf '%s\n' "$jobs" |
jq -c '.[] | select(.ready == true) | {job: .name}'
printf '%s\n' "$jobs" | jq -r '.[0].name'
status=0
printf '%s\n' "$jobs" | jq -e '.[0].owner' || status=$?
printf 'missing owner: exit %s\n' "$status"
status=0
printf '%s\n' "$jobs" |
jq -e '.[] | select(.name == "release")' || status=$?
printf 'no matching job: exit %s\n' "$status"
)
Expected output#
{"job":"lint"}
lint
null
missing owner: exit 1
no matching job: exit 4
Common mistakes#
A missing key and an explicit JSON null both yield null on lookup. Use has("owner") on the object when the distinction matters. A successful filter can emit nothing, so use -e when the shell needs to detect an empty result. Single-quote the filter so the shell passes pipes and other filter syntax through to jq.
Version applicability#
The jq 1.4 manual already documents the example's -c, -r and -e flags. The complete example and its exit statuses were verified with jq 1.8.1.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0