jq · lesson 26 of 32 · Variables & functions

Variables

expr as $name | … binds a value for the rest of the pipeline — handy when you need it twice. A pattern on the left destructures objects and arrays.

Examples

Example 1Average age with a saved count

Document

{
  "team": "Platform",
  "office": { "city": "Berlin", "floor": 3 },
  "members": [
    { "name": "Ada", "age": 36, "role": "lead", "active": true,
      "email": "[email protected]", "skills": ["rust", "sql"] },
    { "name": "Linus", "age": 28, "role": "dev", "active": true,
      "email": null, "skills": ["c", "shell"] },
    { "name": "Grace", "age": 45, "role": "dev", "active": false,
      "skills": ["cobol"] },
    { "name": "Alan", "age": 41, "role": "qa", "active": true,
      "email": "[email protected]", "skills": [] }
  ]
}

Query

.members | length as $n | map(.age) | add / $n
  1. length as $n Compute the length (4) and bind it to $n; the input stays the members array.
  2. map(.age) | add The sum of the ages — . is still the members array here.
  3. / $n Divide by the saved count.

Result

37.5

Try it in the playground

Example 2Destructuring

Document

{
  "team": "Platform",
  "office": { "city": "Berlin", "floor": 3 },
  "members": [
    { "name": "Ada", "age": 36, "role": "lead", "active": true,
      "email": "[email protected]", "skills": ["rust", "sql"] },
    { "name": "Linus", "age": 28, "role": "dev", "active": true,
      "email": null, "skills": ["c", "shell"] },
    { "name": "Grace", "age": 45, "role": "dev", "active": false,
      "skills": ["cobol"] },
    { "name": "Alan", "age": 41, "role": "qa", "active": true,
      "email": "[email protected]", "skills": [] }
  ]
}

Query

. as {team: $t, office: {city: $c}} | "\($t) in \($c)"
  1. {team: $t, office: {city: $c}} A pattern: pull team into $t and office.city into $c in one go.
  2. "\($t) in \($c)" Use the variables like any value — here, inside a string.

Result

"Platform in Berlin"

Try it in the playground

Good to know

  • A variable is visible only to the right of its as, up to the end of the enclosing pipeline or parentheses.

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.