jq is an exceptional tool to parse JSON in command line. In this post, we will go through some of its basic options and usages.
If you are on Ubuntu or Debian, you can install
On macOS, you can install it using Homebrew.
To demonstrate the usage of
jq, we will use the sample JSON data provided by jsonplaceholder.typicode.com. Its
/users endpoint lists 10 sample users in the following format.
curl -s runs
curl in quiet mode and hides the request progress meter.
1. Extract the name from the first user.
'.' refers to the entire JSON object.
'.' refers to the first object in the JSON array.
'. .name' refers to the
name attribute in the first object in the JSON array.
We can use
-r switch in
jq to remove the quotes from the output.
2. Extract the names of all users.
'.' refers to all objects in the JSON array.
3. Extract selected attributes.
Notice how we extract
city field using
.address.city expression. It looks inside
address object to fetch the
city attribute of the user.
4. Extract selected attributes of all users.
Wrapping the expression inside
 encloses the result in an array.
5. Conditionally extract attributes of users.
select function, we can filter through the JSON objects based on a boolean expression. In this example, we are parsing the names of all users with zipcode
jq is quite useful in shell scripts that process JSON data. It has many other features and they all are documented in its manual.