[jq] Handle conversion errors with try and catch

Created on November 30, 2026

Use try … catch … to handle errors raised by jq filters. Here tonumber converts valid numeric strings and catch null fills their unsuccessful conversions with null.

printf '%s\n' '["10","invalid","20"]' | jq 'map(try tonumber catch null)'
[
  10,
  null,
  20
]

This preserves the input array positions, including the position of "invalid".

Skip values that cannot be converted

Omitting catch makes a failed try emit no result.

printf '%s\n' '["10","invalid","20"]' | jq 'map(try tonumber)'
[
  10,
  20
]

try tonumber is equivalent to try tonumber catch empty. The filter handles runtime conversion errors. Malformed input JSON fails during parsing before the filter runs.

Reference

jq