devutils/ATFQ/book ATFQ git

Part III · Shell and commands

28.8 jq

alsojqjsonparse jsonpretty print json

TL;DR

  • jq filters JSON: give it a path, get the value back.
  • . is the whole input, pretty-printed. .name is a field, .items[] each element of an array, and | chains filters.
  • -r prints strings without quotes, ready for the shell.
curl -s https://api.github.com/repos/jqlang/jq | jq .stargazers_count
jq -r '.dependencies | keys[]' package.json
jq '.[] | select(.age > 30) | .name' people.json

Pitfalls

Deep dive 2 questions

How do filters work?

Each filter takes an input and produces zero, one or several outputs. | feeds every output of the left side to the right side. .items[] produces one output per element, so .items[] | .id gives every id.

[ … ] collects outputs back into an array, and {name: .user.login} builds a new object.

Which functions are worth knowing?

select(condition) keeps what matches, map(f) applies a filter to each element, length, keys and sort_by(.field) do what they say. With -r, @csv and @tsv turn arrays into lines a spreadsheet can open:

jq -r '.[] | [.name, .age] | @csv' people.json
Commands
jq
See also
28.2 grep and regex