jq · lesson 11 of 32 · Filtering & conditions

Testing text & arrays

test, startswith, endswith and contains return booleans, so they slot straight into select.

Examples

Example 1Names that start with A or G

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[] | select(.name | test("^[AG]")) | .name
  1. select( Keep only members for which the test is true.
  2. test("^[AG]") A regex match on the piped-in string: ^ anchors at the start and [AG] is one of the letters A or G.

Result

"Ada"
"Grace"
"Alan"

Try it in the playground

Example 2Members with a given skill

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[] | select(.skills | contains(["sql"])) | .name
  1. select( Keep only members for which the test is true.
  2. contains(["sql"]) True when the array includes every element of the argument — here the string "sql".

Result

"Ada"

Try it in the playground

Good to know

  • Also handy: startswith("A"), endswith(".com"), has("email") (does the key exist?) and any(.skills[]; . == "rust") (does some element satisfy the condition?).

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.