Skip to content

Grouping and Aggregating JSON Data ​

Group records by a field, count occurrences, and compute sums, averages, and per-group totals from the terminal. fx does it with groupBy, uniq, len, and plain JavaScript (install fx).

Examples use this orders.json:

json
[
  {"id": 101, "customer": "alice", "category": "books", "total": 24.5},
  {"id": 102, "customer": "bob", "category": "games", "total": 59.99},
  {"id": 103, "customer": "alice", "category": "games", "total": 19.99},
  {"id": 104, "customer": "carol", "category": "books", "total": 12},
  {"id": 105, "customer": "bob", "category": "music", "total": 9.5}
]

Group JSON Array by Field ​

groupBy returns an object: each key is a group, each value is the array of matching records.

bash
fx orders.json 'groupBy(x => x.category)'

Output:

json
{
  "books": [
    { "id": 101, "customer": "alice", "category": "books", "total": 24.5 },
    { "id": 104, "customer": "carol", "category": "books", "total": 12 }
  ],
  "games": [
    { "id": 102, "customer": "bob", "category": "games", "total": 59.99 },
    { "id": 103, "customer": "alice", "category": "games", "total": 19.99 }
  ],
  "music": [
    { "id": 105, "customer": "bob", "category": "music", "total": 9.5 }
  ]
}

Count Items per Group ​

Turn the groups into [key, group] pairs, replace each group with its length, and build an object again:

bash
fx orders.json 'groupBy(x => x.category)' \
  'Object.entries(x).map(([k, g]) => [k, g.length])' \
  'Object.fromEntries'

Output:

json
{
  "books": 2,
  "games": 2,
  "music": 1
}

TIP

The result of groupBy is an object, so iterate it with Object.entries. map(fn) and @ iterate arrays only; on an object they apply fn to the whole object once. See map.

To count only the records that match a condition, filter first and take the length:

bash
fx orders.json '?.customer === "bob"' len
2

Sum Values in a JSON Array ​

Pull the numbers out with @ and reduce them:

bash
fx orders.json '@.total' 'x => x.reduce((a, b) => a + b, 0)'
125.98

Calculate Average, Min, and Max ​

Compute several statistics in one pass:

bash
fx orders.json '@.total' 'x => ({
  sum: x.reduce((a, b) => a + b, 0),
  avg: x.reduce((a, b) => a + b, 0) / x.length,
  min: Math.min(...x),
  max: Math.max(...x)
})'

Output:

json
{
  "sum": 125.98,
  "avg": 25.196,
  "min": 9.5,
  "max": 59.99
}

Sum Values per Group ​

Revenue per customer: group, then sum each group's total. toFixed(2) removes floating-point noise such as 44.489999999999995; the leading + turns the string back into a number.

bash
fx orders.json 'groupBy(x => x.customer)' \
  'Object.entries(x).map(([k, g]) => [k, +g.reduce((s, o) => s + o.total, 0).toFixed(2)])' \
  'Object.fromEntries'

Output:

json
{
  "alice": 44.49,
  "bob": 69.49,
  "carol": 12
}

Get Distinct Values From a JSON Array ​

uniq removes duplicates:

bash
fx orders.json '@.customer' uniq
json
[
  "alice",
  "bob",
  "carol"
]

Add len to count distinct values:

bash
fx orders.json '@.category' uniq len
3

Count Occurrences and Sort by Frequency ​

This requests.ndjson has one JSON object per line:

json
{"path": "/api/users", "status": 200, "ms": 42}
{"path": "/api/orders", "status": 500, "ms": 310}
{"path": "/api/users", "status": 200, "ms": 38}
{"path": "/api/login", "status": 401, "ms": 12}
{"path": "/api/users", "status": 404, "ms": 9}

--slurp (-s) reads all lines into one array (streaming mode). Without it, fx would process each line on its own. Count hits per path, then sort by count, highest first, with sortBy:

bash
cat requests.ndjson | fx -s 'groupBy(x => x.path)' \
  'Object.entries(x).map(([k, g]) => [k, g.length])' \
  'sortBy(x => -x[1])' \
  'Object.fromEntries'

Output:

json
{
  "/api/users": 3,
  "/api/orders": 1,
  "/api/login": 1
}

list prints each array element on its own line, without JSON quoting. Build one tab-separated string per row:

bash
cat requests.ndjson | fx -s 'groupBy(x => x.path)' \
  'Object.entries(x).map(([k, g]) => [k, g.length])' \
  'sortBy(x => -x[1])' \
  '@(x[1] + "\t" + x[0])' list
3	/api/users
1	/api/orders
1	/api/login

To align the columns, pipe the output into column -t:

bash
cat requests.ndjson | fx -s 'groupBy(x => x.path)' \
  'Object.entries(x).map(([path, g]) => [path, g.length, Math.max(...g.map(r => r.ms))].join(" "))' \
  list | column -t
/api/users   3  42
/api/orders  1  310
/api/login   1  12

Summarize NDJSON Logs per Group ​

Build one summary object per group with several aggregates:

bash
cat requests.ndjson | fx -s 'groupBy(x => x.path)' 'Object.entries(x).map(([path, g]) => ({
  path,
  count: g.length,
  avgMs: Math.round(g.reduce((s, r) => s + r.ms, 0) / g.length),
  errors: g.filter(r => r.status >= 400).length
}))'

Output:

json
[
  { "path": "/api/users", "count": 3, "avgMs": 30, "errors": 1 },
  { "path": "/api/orders", "count": 1, "avgMs": 310, "errors": 1 },
  { "path": "/api/login", "count": 1, "avgMs": 12, "errors": 1 }
]

Add Reusable sum and countBy Helpers ​

If you run these aggregations often, define the helpers in .fxrc.js:

js
function sum(xs) {
  return xs.reduce((a, b) => a + b, 0)
}

function countBy(fn) {
  return xs => {
    const counts = {}
    for (const x of xs) counts[fn(x)] = (counts[fn(x)] || 0) + 1
    return counts
  }
}

After that, the commands get shorter:

bash
fx orders.json '@.total' sum
125.98
bash
cat requests.ndjson | fx -s 'countBy(x => x.status)'
json
{
  "200": 2,
  "401": 1,
  "404": 1,
  "500": 1
}

See Also ​