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
length as $nCompute the length (4) and bind it to$n; the input stays the members array.map(.age) | addThe sum of the ages —.is still the members array here./ $nDivide by the saved count.
Result
37.5
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)"
{team: $t, office: {city: $c}}A pattern: pullteaminto$tandoffice.cityinto$cin one go."\($t) in \($c)"Use the variables like any value — here, inside a string.
Result
"Platform in Berlin"
Good to know
- A variable is visible only to the right of its
as, up to the end of the enclosing pipeline or parentheses.