backNovember 20, 2025

jq for beginners

jq is a lightweight command-line tool for parsing, filtering, and transforming JSON. Think of it as sed or awk, but for JSON.

Installing jq

# Ubuntu / Debian
sudo apt install jq

# macOS
brew install jq

# Fedora
sudo dnf install jq

The basics

Given a file book.json:

{
  "title": "jq for beginners",
  "author": "Joost van Meeuwen",
  "year": 2025
}

Pretty-print and colorize JSON with the identity filter .:

cat book.json | jq '.'

Grab a specific field:

cat book.json | jq '.title'
# "jq for beginners"

Add -r for raw output without quotes:

cat book.json | jq -r '.title'
# jq for beginners

Working with arrays

Given books.json:

[
  { "title": "jq for beginners", "year": 2025, "rating": 4.5 },
  { "title": "Docker Deep Dive", "year": 2022, "rating": 4.2 },
  { "title": "The PHP Way", "year": 2023, "rating": 3.8 }
]

Get all titles with .[] to iterate over every element:

cat books.json | jq '.[].title'
# "jq for beginners"
# "Docker Deep Dive"
# "The PHP Way"

Get by index:

cat books.json | jq '.[0]'   # first
cat books.json | jq '.[-1]'  # last

Filtering with select

Only books with a rating above 4:

cat books.json | jq '.[] | select(.rating > 4)'

The | works like a shell pipe, .[] iterates, select() keeps what matches.

Filter on strings:

cat books.json | jq '.[] | select(.title | contains("PHP"))'

Building new objects

Pick specific fields and build new objects:

cat books.json | jq '.[] | { name: .title, published: .year }'
{ "name": "jq for beginners", "published": 2025 }
{ "name": "Docker Deep Dive", "published": 2022 }
{ "name": "The PHP Way", "published": 2023 }

Wrap in [ ] to collect results as an array:

cat books.json | jq '[ .[] | { name: .title, published: .year } ]'

Real-world examples

List running Docker containers with their name and image:

docker inspect $(docker ps -q) | jq '.[] | { name: .Name, image: .Config.Image }'

Grab repo names from the GitHub API:

curl -s https://api.github.com/users/your-username/repos | jq '.[].name'

Cheat sheet

ExpressionWhat it does
.Returns the whole input
.keyGet a field by name
.nested.keyGet a nested field
.[]Iterate over array elements
.[0]Get element by index
.[] | select(.x > 1)Filter elements
{ a: .x, b: .y }Build a new object
[ .[] | .x ]Collect results into an array
lengthCount elements or string length
keysGet an object's keys
sort_by(.x)Sort array by field
-rRaw output (no quotes on strings)

And much more

jq can do much more: group_by, unique, map, recursive descent with .., and even custom functions. Check out the official manual or experiment on jqplay.org.