TExcelTAD

jq in Scripts

At the prompt, jq is a query language. Inside a script it is also a parser and a JSON generator, and it needs the same care as any other command: values from the shell must be passed safely, failures must change the exit status, and output must be shaped for the next step. This lesson covers the flags that make that work.

--arg and --argjson: never splice shell variables into a filter

The tempting way to use a shell variable in a filter is to build the filter string: jq ".items[] | select(.name == \"$name\")". It breaks as soon as the value contains a quote, and it lets the value inject jq code. Pass values as jq variables instead:

bash · try it yourself
cat > users.json <<'JSON'
[{"name": "ada", "uid": 1001, "groups": ["dev"]}, {"name": "o\"brien", "uid": 1002, "groups": ["ops", "dev"]}]
JSON
name='o"brien'
echo "--- spliced into the filter: breaks"
jq -c ".[] | select(.name == \"$name\")" users.json 2>&1 | head -n 1
echo "--- --arg: a string variable"
jq -c --arg name "$name" '.[] | select(.name == $name) | .uid' users.json
echo "--- --argjson: a JSON value (number, bool, object)"
jq -r --argjson min 1002 '.[] | select(.uid >= $min) | .name' users.json
echo "--- \$ENV: read the environment directly"
GROUP=ops jq -r '.[] | select(.groups | index(env.GROUP)) | .name' users.json
--- spliced into the filter: breaks
jq: error: syntax error, unexpected IDENT, expecting ';' or ')' (Unix shell quoting issues?) at <top-level>, line 1:
--- --arg: a string variable
1002
--- --argjson: a JSON value (number, bool, object)
o"brien
--- $ENV: read the environment directly
o"brien

--arg always makes a string, so compare numbers with --argjson (or convert with ($x | tonumber)). env.NAME and $ENV.NAME read environment variables.

Building JSON safely

The same problem in reverse: generating JSON with echo "{\"msg\": \"$msg\"}" produces invalid JSON when $msg contains a quote, a backslash or a newline. jq -n with --arg escapes everything correctly:

bash · try it yourself
msg=
  

disk "/data" is 91% full\nsee runbook'
echo "--- with echo (broken)"
echo "{\"text\": \"$msg\"}" | jq -c . 2>&1 | head -n 1
echo "--- with jq -n (correct)"
jq -nc --arg text "$msg" --arg host web-1 --argjson pct 91 '{text: $text, host: $host, usage: $pct}'
echo "--- from key=value arguments: --args and \$ARGS"
jq -nc '$ARGS.positional | map(split("=") | {(.[0]): .[1]}) | add' --args env=prod region=eu-west-1
--- with echo (broken)
jq: parse error: Invalid numeric literal at line 1, column 22
--- with jq -n (correct)
{"text":"disk \"/data\" is 91% full\nsee runbook","host":"web-1","usage":91}
--- from key=value arguments: --args and $ARGS
{"env":"prod","region":"eu-west-1"}

This is how scripts build request bodies for curl -d @-, Slack and Teams webhook messages, and structured log lines. --args (and --jsonargs) put the remaining command-line arguments in $ARGS.positional.

-e: make "nothing found" a failure

By default jq exits 0 even when a filter produces null or false, so a typo in a key name silently returns null. -e (--exit-status) sets the exit status from the last output: 1 if it was false or null, 4 if there was no output at all, 0 otherwise:

bash · try it yourself
echo '{"status": {"ready": true, "replicas": 3}}' > deploy.json
jq -e '.status.ready' deploy.json > /dev/null;        echo "ready:              status $?"
jq -e '.status.raedy' deploy.json > /dev/null;        echo "typo, null:         status $?"
jq -e '.status.replicas >= 5' deploy.json > /dev/null; echo "replicas >= 5:      status $?"
jq -e 'empty' deploy.json > /dev/null;                echo "no output:          status $?"
echo 'not json' | jq -e . > /dev/null 2>&1;           echo "invalid JSON:       status $?"
if jq -e '.status.ready' deploy.json > /dev/null; then echo "deployment is ready"; fi
ready:              status 0
typo, null:         status 1
replicas >= 5:      status 1
no output:          status 4
invalid JSON:       status 5
deployment is ready

Use -e whenever a jq result decides what a script does next, or whenever an extracted value must exist: image=$(jq -er '.image' config.json) fails instead of setting image to the string null.

Reading jq output into Bash safely

Iterating over $(jq -r …) with for splits on spaces. Read one value per line with mapfile, or emit TSV and read several fields at once:

bash · try it yourself
cat > hosts.json <<'JSON'
[{"name": "web 1", "ip": "10.0.0.11", "port": 80}, {"name": "db", "ip": "10.0.0.20", "port": 5432}]
JSON
echo "--- wrong: for over \$(...)"
for h in $(jq -r '.[].name' hosts.json); do echo "[$h]"; done
echo "--- mapfile: one element per line"
mapfile -t names < <(jq -r '.[].name' hosts.json)
printf '[%s]\n' "${names[@]}"
echo "--- several fields per record with @tsv"
while IFS=
  

\t' read -r name ip port; do
  echo "check $name at $ip:$port"
done < <(jq -r '.[] | [.name, .ip, .port] | @tsv' hosts.json)
--- wrong: for over $(...)
[web]
[1]
[db]
--- mapfile: one element per line
[web 1]
[db]
--- several fields per record with @tsv
check web 1 at 10.0.0.11:80
check db at 10.0.0.20:5432

Slurping and JSON Lines

Logs and many APIs produce JSON Lines: one JSON value per line. jq reads such a stream naturally, one value at a time; -s (slurp) collects the whole stream into an array first, which you need for counting or sorting. -c writes JSON Lines back out:

bash · try it yourself
cat > events.jsonl <<'JSON'
{"ts": "2026-01-15T10:00:01Z", "level": "info",  "msg": "started"}
{"ts": "2026-01-15T10:00:04Z", "level": "error", "msg": "db timeout"}
{"ts": "2026-01-15T10:00:09Z", "level": "error", "msg": "db timeout"}
{"ts": "2026-01-15T10:00:12Z", "level": "warn",  "msg": "slow query"}
JSON
echo "--- stream: one value at a time"
jq -c 'select(.level == "error") | {ts, msg}' events.jsonl
echo "--- slurp: count per level"
jq -sc 'group_by(.level) | map({(.[0].level): length}) | add' events.jsonl
echo "--- merge two JSON files (later wins)"
echo '{"replicas": 2, "image": "api:1.4"}' > base.json
echo '{"replicas": 4}' > prod.json
jq -sc '.[0] * .[1]' base.json prod.json
--- stream: one value at a time
{"ts":"2026-01-15T10:00:04Z","msg":"db timeout"}
{"ts":"2026-01-15T10:00:09Z","msg":"db timeout"}
--- slurp: count per level
{"error":2,"info":1,"warn":1}
--- merge two JSON files (later wins)
{"replicas":4,"image":"api:1.4"}

* merges objects recursively (nested objects are merged too), + only at the top level. Merging a base config with an environment override is a one-liner.

Test yourself

Why pass a shell variable with jq --arg name "$name" '... $name ...' instead of putting $name inside the filter string?

  1. It is faster
  2. The value is passed as data, so quotes or jq syntax in it cannot break or change the filter
  3. jq cannot read double-quoted filters
  4. --arg converts strings to numbers

What exit status does jq -e '.status.raedy' return when the key does not exist?

  1. 0
  2. 1, because the last output was null
  3. 4
  4. 5

Which option makes jq read a stream of JSON Lines into a single array?

  1. -c
  2. -r
  3. -s
  4. -n