Skip to main content

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

FlagMeaning
-rRaw output — strip quotes from strings
-cCompact output — single line
-eExit 1 if output is null or false
-nNo input — use null as input
-sSlurp — read all input into one array
--arg k vBind string variable $k = v
--argjson k jBind 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

PitfallConsequencePrevention
No quotes around filterShell expands special charsAlways single-quote: jq '.'
Not using -r in scriptsVariable contains "quotes"Add -r when assigning to bash variable
Accessing missing keyReturns null, no errorUse -e flag to treat null as error
Non-JSON inputParse errorValidate input first

What's Next