JMESPath · lesson 13 of 15 · Functions

Sorting & picking

sort_by, min_by and max_by take an expression reference: &age means "evaluate age on each element" rather than evaluating it right now.

Examples

Example 1Sort by a field

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

sort_by(members, &age)[*].name
  1. sort_by( Sort an array by a key…
  2. members …this array…
  3. &age …the key, as a reference: & postpones age so it is evaluated on every element.
  4. [*].name Then project the names, youngest first.

Result

["Linus","Ada","Alan","Grace"]

Try it in the playground

Example 2The element with the largest value

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

max_by(members, &age).name
  1. max_by(members, &age) The member with the largest age — the whole object.
  2. .name Read its name → "Grace".

Result

"Grace"

Try it in the playground

Good to know

  • sort(list) sorts plain values and reverse(list) flips a list: reverse(sort_by(members, &age))[*].name sorts oldest first.
  • min_by is the counterpart of max_by.

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.