jq Installation and Basics
Learning Focus
jq is the essential CLI tool for working with JSON — think of it as sed and awk combined, but for structured JSON data.
Installation
# Debian / Ubuntu
sudo apt-get install -y jq
# macOS (Homebrew)
brew install jq
# Alpine Linux
apk add jq
# Verify
jq --version
Core Concept
jq reads JSON from stdin or a file, applies a filter expression, and writes JSON to stdout.
jq '<filter>' [file...]
Identity Filter .
Pretty-print the input:
echo '{"name":"Alice","age":30}' | jq '.'
Field Access
echo '{"name":"Alice","age":30}' | jq '.name' # "Alice"
echo '{"user":{"id":1,"email":"a@b.com"}}' | jq '.user.email' # "a@b.com"
# Optional (non-error on missing key)
echo '{"a": 1}' | jq '.b?' # null
Array Operations
echo '[10,20,30]' | jq '.[1]' # 20
echo '[10,20,30]' | jq '.[-1]' # 30 (last)
echo '[1,2,3,4,5]' | jq '.[2:4]' # [3,4]
echo '[1,2,3]' | jq 'length' # 3
echo '[1,2,3]' | jq '.[]' # iterates each
Output Flags
| Flag | Meaning |
|---|---|
-r | Raw output — strip quotes from strings |
-c | Compact output — single line |
-e | Exit 1 if output is null or false |
-n | No input — use null as input |
-s | Slurp — read all input into one array |
--arg k v | Bind string variable $k = v |
--argjson k j | Bind JSON variable $k = j |
# -r: strip quotes for shell variable assignment
NAME=$(echo '{"name":"Alice"}' | jq -r '.name')
echo $NAME # Alice
# -c: compact for storing or piping
echo '{"a":1}' | jq -c '.' # {"a":1}
Concept Map
Concept Flow
jq command
├── filter expression
│ ├── . identity (pretty print)
│ ├── .field field access
│ ├── .[] iterate array
│ └── .[n] index
└── output flags
├── -r raw string output
└── -c compact (single line)
Common Pitfalls
| Pitfall | Consequence | Prevention |
|---|---|---|
| No quotes around filter | Shell expands special chars | Always single-quote: jq '.' |
Not using -r in scripts | Variable contains "quotes" | Add -r when assigning to bash variable |
| Accessing missing key | Returns null, no error | Use -e flag to treat null as error |
| Non-JSON input | Parse error | Validate input first |
What's Next
- Next: jq Filters and Transformations — Select, map, reduce, and construct new JSON.
- Section Overview — Return to the jq CLI module index.