The jq command

Command-line JSON processor 22 examples from the lessons of the IVski Linux Playground — try them in the terminal next to them.

Options in the examples

--raw-output / -r:
With this option, if the filter´s result is a string then it will be written directly to standard output rather than being formatted as a…
--compact-output / -c:
By default, jq pretty-prints JSON output.

Examples

jq . ~/json/servers.json

the whole file, indented

jq .updated ~/json/servers.json

one field

jq '.servers[0]' ~/json/servers.json

the first server

jq '.servers[0].ip' ~/json/servers.json

a field of it

jq '.servers[].name' ~/json/servers.json

"web01" "web02" ...

jq -r '.servers[].name' ~/json/servers.json

-r: raw text, no quotes

jq '.servers | length' ~/json/servers.json

how many

jq '.servers[] | select(.status == "stopped") | .name' ~/json/servers.json
jq '[.servers[].ram_gb] | add' ~/json/servers.json

total RAM

jq '.servers[] | {name, ip}' ~/json/servers.json

just these fields

jq -c '.servers[] | {name, ram: .ram_gb}' ~/json/servers.json

-c: one line each

jq -r '.servers[] | "\(.name) has \(.ram_gb) GB"' ~/json/servers.json
jq -r '.servers[] | [.name, .ip, .status] | @csv' ~/json/servers.json
curl -s https://api.example.com/servers | jq '.servers[] | select(.status != "running") | .name'
curl -s http://localhost:5000/api/orders | jq .
curl -s http://localhost:5000/api/orders | jq '.orders[0]'
curl -s http://localhost:5000/api/orders | jq '.orders | length'
curl -s http://localhost:5000/api/orders | jq '[.orders[] | select(.status == "paid") | .total] | add'
curl -s http://localhost:5000/api/orders | jq -r '.orders[] | select(.status == "pending") | "\(.id) \(.customer)"'
jq '[.orders[] | select(.status == "paid") | .items[]] | group_by(.product) | map({product: .[0].product, qty: (map(.qty) | add)}) | sort_by(-.qty)' /tmp/orders.json
curl -s http://localhost:5000/api/orders | jq '{
jq -r '.orders[] | select(.status == "paid") | [.id, .customer, .total] | @csv' /tmp/orders.json > ~/reports/paid.csv

Lessons that use jq

Related commands