jq · lesson 20 of 32 · Aggregation

limit, first & range

limit(n; stream) and first(stream) stop as soon as they have enough, instead of computing everything. range generates numbers.

Examples

Example 1At most two names

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

limit(2; .members[] | .name)
  1. limit(2; Take at most 2 outputs from the stream after the ;, then stop evaluating.
  2. .members[] | .name The stream being limited: every member's name.

Result

"Ada"
"Linus"

Try it in the playground

Example 2The first match only

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

first(.members[] | select(.age > 40)).name
  1. first( The first output of the stream inside — evaluation stops right there.
  2. select(.age > 40) The stream: members older than 40.
  3. .name Read the name of that one result.

Result

"Grace"

Try it in the playground

Good to know

  • range(n) counts from 0: [range(3)] is [0,1,2], and [range(1; 10; 4)] steps by 4 → [1,5,9].
  • Because they stop early, limit and first stay fast even on huge inputs.

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.