jq · lesson 31 of 32 · Errors

try, catch & ?

Some filters fail on some inputs — tonumber on "two", for instance. try f catch g recovers with a fallback, and f? simply drops the failure.

Examples

Example 1A fallback for bad input

Document

["1", "two", "3"]

Query

.[] | try tonumber catch "n/a"
  1. try tonumber Run tonumber; if it raises an error…
  2. catch "n/a" …produce this instead. Inside catch, . is the error message.

Result

1
"n/a"
3

Try it in the playground

Example 2Silently skip failures

Document

["1", "two", "3"]

Query

[.[] | tonumber?]
  1. tonumber? A trailing ? is try without a catch: values that fail just produce no output.

Result

[1,3]

Try it in the playground

Good to know

  • error("message") raises your own error: try error("boom") catch "caught" gives "caught".

About jsonquery

Query, format and learn JSON with jq, JSONPath, JMESPath and JSON Pointer. It is the engine of the desktop app, run in your browser.

Engine
The desktop app’s, compiled to WebAssembly
Licence
MIT (the engine and the app)
Source
GitHub
Contact
The contact form (private)
Public issues
GitHub
Legal
Privacy policy

Known limitations: a file over 10 MB opens read-only and one over 512 MB does not open here; the desktop app has no such limit.