---
name: jq-json
description: 'Query and transform JSON with jq 1.7: select/map/group_by, building objects, merging, updating in place, converting to CSV/TSV, passing shell variables safely with --arg/--argjson, reading large files. Use when the user needs to extract fields from an API response, reshape or validate JSON, or edit a JSON config from a script. Triggers: jq، parse json، json to csv، filter json in bash.'
---

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

## Workflow

1. Look at the shape first: `jq 'keys'`, `jq '.[0]'`, `jq 'type'`.
2. Build the filter step by step, piping `|` stage by stage.
3. Use `-r` for plain text output, `-c` for one JSON value per line, `-e` to make a missing result a non-zero exit.
4. Never splice shell variables into the filter; pass them with `--arg`.
5. 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.json
```

## Convert

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

## Gotchas

- Single-quote filters in bash; use `--arg` instead of double-quote interpolation.
- Numbers beyond 2^53 are preserved as written in 1.7 unless you do arithmetic on them.
- `jq . file > file` truncates the input before it is read; always use a temp file.
- `.[]` on an object iterates values, on `null` it errors; use `.[]?`.
- Output of `@csv` quotes strings only; `@tsv` escapes 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
```
