jq · lesson 27 of 32 · Variables & functions

Your own functions

def name(params): body; defines a reusable filter. A parameter written $n receives a value; a plain name receives a filter.

Examples

Example 1A reusable filter

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

def older($n): select(.age > $n); .members[] | older(30) | .name
  1. def older($n): Define a filter called older with one value parameter.
  2. select(.age > $n) Its body: reuse select, comparing with the parameter.
  3. ; Ends the definition.
  4. older(30) Call it like any built-in filter.

Result

"Ada"
"Grace"
"Alan"

Try it in the playground

Good to know

  • Parameters without a $ are filters, not values: def twice(f): f | f; then 3 | twice(. + 1) gives 5.

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.