Companion cheatsheet with every recipe: jq quick reference — knowledge base entry.
You have JSON from an API, a CLI, a config file — and you need three fields out of it, flattened, without writing a script. That's the jq sweet spot: it reads JSON, applies a small filter language, and prints exactly what you asked for. Below are the patterns I reach for daily.
Reading fields
jq '.field' # one field jq '.a.b.c' # nested jq '.items[0]' # first array element jq '.[]' # every element
Shaping output
jq '.[] | {name, id}' # object per element
jq -r '.[] | [.id, .name] | @tsv' # tab-separated rows
jq 'map(.name) | unique | sort' # dedupe + sort
Filtering
jq '.[] | select(.x > 5)'
jq 'first(.[] | select(.active))'
jq '.[] | select(.name | test("^harbour-"))'
gh api + jq — the power combo
gh api 'orgs/ORG/repos?per_page=100' --jq '.[].name' gh api repos/ORG/REPO/git/trees/main?recursive=1 --jq '.tree[].path'
--jq on gh api is exactly the same as piping to
jq — it just saves a pipe.
Gotchas that bite everyone
.foo.bardies on a null parent — use.foo?.baror.foo // {}select()filters,map()transforms — mixing them up is the #1 mistake@tsv/@csvneed-ror the output looks wrong- Piping one jq into another? Stay in JSON mode — only add
-rat the end.
The full table of recipes — aggregation, objects, interpolation, conditionals — is in the KB entry.
No comments:
Post a Comment