← All cheatsheets

Shell + Data

jq — JSON processing on the command line

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

```bash
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

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

## Transformation

```bash
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

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

## Output formats

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

## Real workflows

```bash
# 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.