jq · lesson 7 of 32 · Pipes & building output
Strings & interpolation
"…\(expr)…" inserts the result of any filter into a string. Combine it with join, ascii_downcase, sub and friends for text work.
Examples
Example 1Format a line of text
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
"\(.team) @ \(.office.city), floor \(.office.floor)"
\(.team)Interpolation: anything inside\( )is a full jq filter whose result is inserted into the string.\(.office.city)Nested paths work too.\(.office.floor)Numbers are converted to text automatically.
Result
"Platform @ Berlin, floor 3"
Example 2Join and change case
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 | map(.name | ascii_downcase) | join(", ")
map(Apply the filter inside to every member…ascii_downcase…lower-casing each name…join(", ")…then glue the array of strings into one string with a separator.
Result
"ada, linus, grace, alan"
Good to know
- More string filters:
split(","),ltrimstr,startswith,endswith,test("regex"),length, andsub/gsubfor regex replacement. - For example
.members[0].email | sub("@.*"; "@corp.io")gives"[email protected]".