jq ftw II
Well, my affinity for shell scripting shows no sign of slowing down. Today I found out some more cool stuff that is possible with the jq
utility.
In addition to the easy handling of raw JSON, jq
also provides classic functional operators like map
, reduce
and filter
which can be chained together.
To facilitate, there’s a fantastic website called jqplay which I highly recommend!
Here’s a quick example of how to curl some API data and transform it into a format that can be easily bash’ed with.
Sample of input data from https://jsonplaceholder.typicode.com/:
(api returns 10 at a time, this is just one sample)
The command:
Notes:
- The
curl
request returns an array of objects - Each object is yielded to
map
map
returns an array for each object, composed ofwebsite
andid|tostring
(nice pipe function to turn int into string)- each array is flattened into a new string with
=>
symbol in between - then the whole array is flattened into a string of elements separated by new line characters
Output:
We can use the read/while
loop described yesterday to loop over this data and do whatever we want with it. For example, we can use the original call to gather the elements needed to compose URLs, then we can build the URLs dynamically in the loop and fetch the data.