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
select(Keep only members for which the test is true.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"
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
select(Keep only members for which the test is true.contains(["sql"])True when the array includes every element of the argument — here the string"sql".
Result
"Ada"
Good to know
- Also handy:
startswith("A"),endswith(".com"),has("email")(does the key exist?) andany(.skills[]; . == "rust")(does some element satisfy the condition?).