jq · lesson 12 of 32 · Filtering & conditions
Missing values: // and empty
a // b gives a unless it is null, false or produces nothing — then it gives b. empty produces no output at all, which makes it a way to drop values.
Examples
Example 1A default for missing e-mail
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[] | .email // "n/a"
.emailAda and Alan have one, Linus hasnull, and Grace has no such key at all.// "n/a"The alternative operator: use the right side when the left isnull,falseor missing.
Result
"[email protected]" "n/a" "n/a" "[email protected]"
Example 2Drop the missing ones
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[] | .email // empty]// emptyemptyoutputs nothing, so members without an e-mail simply vanish from the stream.
Result
["[email protected]","[email protected]"]
Good to know
has("email")only checks that the key exists: Linus has it (with the valuenull), Grace doesn't.select(.email)skips both.