$ cat ./posts/oct-22,-2021

jq cheatsheet

A quick reference for jq — the lightweight and flexible command-line JSON processor.

#linux#cli#json

jq is a lightweight and flexible command-line JSON processor, it is also described as sed for JSON data: You can use it to slice and filter and map and transform structured data with the same ease.

We’ll use below endpoint as example https://reqres.in/api/users which provides response in json format.

Beautify json

curl https://reqres.in/api/users | jq .
curl https://reqres.in/api/users | jq .page

output:

1
curl 'https://reqres.in/api/users' | jq .data
curl 'https://reqres.in/api/users' | jq '.data[] | {first_name,last_name}'
curl 'https://reqres.in/api/users' | jq '.data[].first_name'
curl 'https://reqres.in/api/users' | jq '.data[] | {first_name,last_name} | join(" ")'

Get all records for person with first_name Eve

curl 'https://reqres.in/api/users' | jq '.data[] | select(.first_name == "Eve")'

Get email of a person with first_name Eve

curl 'https://reqres.in/api/users' | jq '.data[] | select(.first_name == "Eve") | {email}'

Extract all keys from json

curl 'https://reqres.in/api/users' | jq keys
curl 'https://reqres.in/api/users' | jq '.data[1:3]'

Sort array data by first_name

curl 'https://reqres.in/api/users' | jq '.data | sort_by(.first_name)'

Count elements in subscripted array data

curl 'https://reqres.in/api/users' | jq '.data | length'

output:

6

Try these examples here as well — json is pre-loaded.