jq cheatsheet

Control & advanced

Variables, conditions, errors, paths, and reductions. Explore 6 examples, then try one against the included input or your own data.

jq examples

6 examplesVariables, conditions, errors, paths, and reductions.
Control & advanced

Bind a value to a variable

as binds a value while letting the remaining pipeline keep its original input.

. as $root | .users[] | {name, team: $root.team}
Input and expected output
Input
{"team":"compiler","users":[{"name":"Ada"},{"name":"Grace"}]}
Expected output
{
  "name": "Ada",
  "team": "compiler"
}
{
  "name": "Grace",
  "team": "compiler"
}
Control & advanced

Choose a value with if/then/else

Conditions are filters and must end with end.

if .score >= 90 then "excellent" elif .score >= 70 then "pass" else "retry" end
Input and expected output
Input
{"score":84}
Expected output
"pass"
Control & advanced

Recover from an error

try/catch turns an error into a value you can handle deliberately.

try (.value | tonumber) catch "not a number"
Input and expected output
Input
{"value":"unknown"}
Expected output
"not a number"
Control & advanced

List paths to scalar values

paths emits path arrays; scalars limits them to leaf-like values.

[paths(scalars)]
Input and expected output
Input
{"user":{"name":"Ada","active":true},"count":2}
Expected output
[
  [
    "user",
    "name"
  ],
  [
    "user",
    "active"
  ],
  [
    "count"
  ]
]
Control & advanced

Find matching fields recursively

.. walks every descendant; objects selects only values that can have a name field.

.. | objects | .name? // empty
Input and expected output
Input
{"name":"root","children":[{"name":"first"},{"nested":{"name":"second"}}]}
Expected output
"root"
"first"
"second"
Control & advanced

Build an index with reduce

reduce folds a stream into a single accumulated value.

reduce .users[] as $user ({}; .[$user.id] = $user.name)
Input and expected output
Input
{"users":[{"id":"u1","name":"Ada"},{"id":"u2","name":"Grace"}]}
Expected output
{
  "u1": "Ada",
  "u2": "Grace"
}