jq · lesson 10 of 32 · Filtering & conditions
if / elif / else
if … then … elif … else … end picks one branch per input. Every condition and branch is itself a filter.
Examples
Example 1Label each member by age
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[] | if .age >= 40 then "senior" elif .age >= 30 then "mid" else "junior" end
if .age >= 40The first condition.then "senior"Its result when it is true.elif .age >= 30Otherwise, try the next condition.then "mid"Its result.else "junior"The result when nothing above matched.endEveryifis closed withend.
Result
"mid" "junior" "senior" "senior"
Good to know
ifyields a value, so it can sit anywhere a filter can — insidemap(…),select(…)or an object value.