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
  1. if .age >= 40 The first condition.
  2. then "senior" Its result when it is true.
  3. elif .age >= 30 Otherwise, try the next condition.
  4. then "mid" Its result.
  5. else "junior" The result when nothing above matched.
  6. end Every if is closed with end.

Result

"mid"
"junior"
"senior"
"senior"

Try it in the playground

Good to know

  • if yields a value, so it can sit anywhere a filter can — inside map(…), select(…) or an object value.

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.