pexels vovaflame 3673513

jq for Real Work: Slicing JSON on the Command Line

Every API, every container runtime and half the CLI tools you use now speak JSON. jq is the tool that makes that usable from a shell: a small, fast filter language that takes JSON in, and gives you exactly the fields you asked for out. It takes an afternoon to get comfortable with and then it is permanent.

Installing jq

# macOS
brew install jq

# Debian / Ubuntu
sudo apt update && sudo apt install jq

jq --version

Check you are on 1.7 or later. It added --args, proper ltrimstr/rtrimstr handling of non-strings and a pile of fixes; Debian 12 ships 1.6, which is fine but will trip you up on a couple of newer examples.

The syntax you will actually use

jq programs are filters joined by pipes, exactly like a shell pipeline. Nine constructs cover the vast majority of real work:

  • . the whole document — jq . on its own is a pretty-printer and validator.
  • .name a field, .a.b.c a nested one, .name? the version that does not error when it is missing.
  • .[] iterate an array, turning one input into many outputs.
  • select(...) filter — select(.state == "open").
  • map(...) apply a filter to every element and stay an array.
  • {a: .x, b: .y} build a new object; [...] build an array.
  • -r raw output — strings without quotes, which is what you want before piping anywhere else.
  • @tsv and @csv turn an array into a delimited line.
  • // the alternative operator: .nickname // .name // "unknown".

Also worth knowing early: --arg name value passes a shell variable in safely rather than you splicing strings into the filter, and -c prints one compact object per line, which is the format every other Unix tool wants.

Parsing a real API response

Here is the job as it actually turns up: which open pull requests on a repo are waiting on me, and how old are they? Start by exploring — keys on the first element tells you what you have without reading the docs.

curl -s https://api.github.com/repos/cli/cli/pulls | jq '.[0] | keys'

Then narrow it to the fields you care about and shape it into a table:

curl -s https://api.github.com/repos/cli/cli/pulls \
  | jq -r '.[]
      | select(.draft == false)
      | [.number, .user.login, (.created_at | split("T")[0]), .title]
      | @tsv' \
  | column -t -s $'\t'

Add --arg who "$USER" and select(.user.login == $who) and you have a personal dashboard in one line. Swap @tsv for @csv and you have something to hand to a spreadsheet.

Filtering structured logs

If your application logs JSON lines, jq is a far better filter than grep because it understands the fields. select on level, pull out the message, keep the timestamp:

tail -f /var/log/app/app.log \
  | jq -r --unbuffered 'select(.level == "error") | "\(.ts) \(.request_id) \(.msg)"'

--unbuffered is essential when following a stream, otherwise jq holds output back and the tail appears to hang. For a one-off count of the noisiest endpoints, group_by does the aggregation:

jq -s -r 'group_by(.path) | map({path: .[0].path, n: length})
          | sort_by(-.n) | .[:10][] | "\(.n)\t\(.path)"' app.log

The same trick works on local tooling. Docker reports disk usage as JSON, so a single filter tells you where the space went — handy alongside the rest of a practical guide to freeing up disk space on Linux.

docker system df --format json | jq -r '"\(.Type)\t\(.Size)\t\(.Reclaimable)"'

Shell integration

Two aliases and one habit. The aliases:

alias jqk='jq -r "keys"'      # what fields does this thing have?
alias jql='jq -c .'           # one object per line, ready to pipe

The habit: build filters incrementally in the shell. Run jq '.', then jq '.items', then jq '.items[] | .name'. Trying to write the finished filter in one go is how you end up staring at a Cannot index array with string error. And keep long filters in a file, run with jq -f report.jq, once they outgrow a single line.

When jq is the wrong tool

  • When the CLI already does it. gh pr list --json number,title --jq '.[].title' has jq built in, and kubectl -o jsonpath saves a pipe. Use the native flag first.
  • Multi-gigabyte files. jq loads a document into memory unless you use --stream, and --stream syntax is genuinely unpleasant. Reach for Python at that point.
  • Real business logic. If the filter needs comments to be understood, it should be a script in a language your colleagues read.
  • Not-quite-JSON input. Trailing commas, NDJSON with blank lines, log files with a text prefix — clean the input first rather than fighting the parser.

The verdict

Learn .[], select, -r and @tsv and you have covered most of what jq gets used for. Build filters one stage at a time, pass shell values in with --arg, and hand anything genuinely complicated to a proper script. It is the difference between JSON being something you squint at and something you can pipe.


Leave a Reply