Processing JSON with jq: filters, transforms and safe shell usage
A practical jq 1.7 cheat sheet for selecting, reshaping, merging and converting JSON from files, APIs and CLI output, with the quoting pitfalls that break scripts.
Install in Claude Code
Put the file in a folder named after the skill inside Claude Code's skills folder, then start a new session. This command does it:
bash
mkdir -p ~/.claude/skills/jq-json && \
curl -fsSL https://md2.dev/library/raw/jq-json.md \
-o ~/.claude/skills/jq-json/SKILL.md Preview
Processing JSON with jq
When to use
Whenever JSON must be read or changed from the command line: API responses, wrangler ... --json output, package files, logs in JSON lines.
BASH
jq --version # jq-1.7.xWorkflow
- Look at the shape first:
jq 'keys',jq '.[0]',jq 'type'. - Build the filter step by step, piping
|stage by stage. - Use
-rfor plain text output,-cfor one JSON value per line,-eto make a missing result a non-zero exit. - Never splice shell variables into the filter; pass them with
--arg. - Write edits to a temp file, then move it over the original.
Core filters
BASH
jq '.' # pretty print
jq -r '.user.name' # raw string
jq '.items[] | {id, title}' # project fields
jq '.items | map(select(.price > 10))' # filter an array
jq '[.items[] | .price] | add' # sum
jq '.items | length'
jq '.items | sort_by(.date) | reverse | .[0:3]'
jq '.items | group_by(.type) | map({type: .[0].type, n: length})'
jq '.items | unique_by(.id)'
jq '.a // "default"' # default for null or false
jq '.items[]? | .tags[]?' # tolerate missing or null
jq 'pick(.id, .name)' # 1.7: keep only these keys
jq 'paths(type == "string")' # discover where strings live
jq '[.. | strings] | map(select(test("error"; "i")))'Safe variables
BASH
jq --arg name "$USER_NAME" '.users[] | select(.name == $name)' users.json
jq --argjson limit 5 '.items[:$limit]' data.json # numbers and booleans
jq -n --rawfile md README.md '{markdown: $md, format: "pdf"}'
jq -n --arg a "$A" --arg b "$B" '{a: $a, b: $b}'
jq -n '$ENV.HOME'--arg always gives a string; use --argjson for numbers. --rawfile and --slurpfile read files as a string or JSON.
Edit and merge
BASH
jq '.version = "2.0.0"' package.json > tmp && mv tmp package.json
jq '.scripts.build |= "tsc -p ."' package.json
jq 'del(.devDependencies.typescript)' package.json
jq '.tags += ["new"]' item.json
jq -s '.[0] * .[1]' base.json override.json # deep merge
jq -s 'add' a.json b.json # concat arrays or merge objects
jq 'with_entries(select(.value != null))' obj.json # drop null keys
jq 'to_entries | map("\(.key)=\(.value)") | .[]' -r obj.jsonConvert
BASH
# JSON array of objects to CSV with a header
jq -r '(.[0] | keys_unsorted) as $k | $k, (.[] | [.[$k[]]]) | @csv' rows.json
# CSV (simple, no embedded commas) to JSON
jq -R -s 'split("\n") | map(select(length > 0) | split(",")) | .[0] as $h | .[1:] | map([$h, .] | transpose | map({(.[0]): .[1]}) | add)' data.csv
jq -r '.[] | [.id, .name] | @tsv' rows.json
jq -r '@base64d' <<< '"aGVsbG8="'
jq -rn '"a b" | @uri'JSON lines and big files
BASH
jq -c 'select(.level == "error")' app.log # one object per line in, per line out
jq -s 'group_by(.user) | map({user: .[0].user, n: length})' app.log # slurp: needs memory
jq --stream -n 'fromstream(1 | truncate_stream(inputs))' huge.json # constant memoryGotchas
- Single-quote filters in bash; use
--arginstead of double-quote interpolation. - Numbers beyond 2^53 are preserved as written in 1.7 unless you do arithmetic on them.
jq . file > filetruncates the input before it is read; always use a temp file..[]on an object iterates values, onnullit errors; use.[]?.- Output of
@csvquotes strings only;@tsvescapes tabs and newlines.
Verify
BASH
jq -e . file.json > /dev/null && echo valid # syntax check, non-zero when invalid
jq -e '.items | length > 0' resp.json # assert a condition in scripts