3 ms·
I always struggled with understanding JQ. Each time I was just googling things. But actually it does make a lot of sense if you understanding the building block
by adamgordonbell 3y ago
I always struggled with understanding JQ. Each time I was just googling things. But actually it does make a lot of sense if you understanding the building blocks. I wrote it all down [1] but here is my summary:
jq lets you select elements like it's a JavaScript object using dot notation and array indexing.
jq '.key.subkey.subsubkey'
jq '.key[].subkey[2]'
You can turn wrap things in array constructors, or object constructors to create new objects and lists:
jq '[ .[].key ]'
jq '{key1: .key1, key2: .key2}'
You can combine filters with pipes (|) to build complex transformations. Built-ins like map() and select() are useful for transforming arrays.
You put it all together into something like this:
curl https://api.github.com/repos/stedolan/jq/issues |
jq 'map({title: .title, labels: .labels}) |
map(select(.labels)) |
map({issue: .title}) |
sort_by(.issue) |
[{issues: .[]}]
This query fetches GitHub issues, transforms them into a simplified structure, filters out unlabeled issues, sorts them, and wraps the results in an array - demonstrating how you can chain together jq's query language to wrangle JSON data.
[1]: https://earthly.dev/blog/jq-select/ https://earthly.dev/blog/jq-select/
- kspacewalk2 3y agoHad to add `-L` to the curl command to follow redirects, since their API endpoints seem to have changed.