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.jsonthe whole file, indented
jq .updated ~/json/servers.jsonone field
jq '.servers[0]' ~/json/servers.jsonthe first server
jq '.servers[0].ip' ~/json/servers.jsona 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.jsonhow many
jq '.servers[] | select(.status == "stopped") | .name' ~/json/servers.json
jq '[.servers[].ram_gb] | add' ~/json/servers.jsontotal RAM
jq '.servers[] | {name, ip}' ~/json/servers.jsonjust 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