jq · lesson 17 of 32 · Aggregation

Counting & math

Arrays have length, add, min and max, and the usual arithmetic works: + - * / %.

Examples

Example 1Count, total, average, extremes

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 | map(.age) | (length, add, add / length, min, max)
  1. map(.age) An array of just the ages: [36,28,45,41].
  2. length How many elements → 4.
  3. add The sum → 150.
  4. add / length The average → 37.5.
  5. min, max The smallest and the largest → 28, 45.

Result

4
150
37.5
28
45

Try it in the playground

Good to know

  • min_by(.age) and max_by(.age) return the whole element, not just the number.
  • floor and round are there for rounding.

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.