← All cheatsheets

Shell + Data

jq — JSON processing on the command line

jq for JSON on the command line: pretty-print, filter with select, reshape objects, group and sort, update fields, and parse API responses.

jq is the awk of JSON. Master 10 patterns and you have a Swiss army knife for API responses, config files, and log streams.

Basics

echo '{"name":"Alice","age":30}' | jq .            # pretty print
echo '[1,2,3]' | jq '.[]'                          # iterate
echo '{"a":1,"b":2}' | jq '.a'                     # extract field
echo '{"a":1,"b":2}' | jq '. | keys'               # list keys

Filtering

jq 'select(.age > 25)' users.json
jq '.[] | select(.role == "admin")'
jq '[.[] | select(.active)]'                       # back to array

Transformation

jq '{name, age}' users.json                        # pick fields
jq '.users | map(.email)'                          # collect emails
jq '.users | map({name, email}) | .[]'             # extract + iterate
jq '. | to_entries | map(.value) | add'            # sum values

Joining + grouping

jq 'group_by(.department) | map({dept: .[0].department, count: length})'
jq 'unique_by(.email)'
jq 'sort_by(.created_at) | reverse'

Output formats

jq -r '.name'                                       # raw (no quotes)
jq -c '.'                                           # compact (one line)
jq -s '.'                                           # slurp (array of inputs)

Update in place

jq '.items | length' file.json                      # array length
jq '. + {new_field: "value"}' file.json             # add a field
jq '.field |= ascii_downcase' file.json             # transform a field
jq -r '.[] | .name + " <" + .email + ">"'           # string concat

Real workflows

# pull all repo names from GH api
curl ... | jq -r '.[].name'

# count errors by source from logs
cat logs.json | jq -r '.[] | select(.level=="error") | .source' | sort | uniq -c

Tip

If jq feels hard, write the transform in jq with comments, then hand it to AI: "explain what this jq filter does step by step." Reading is easier than writing.