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:
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:
msg=