jq
is a powerful command-line JSON processor that makes it easy to extract, transform, and query structured data. Below is a compact cheatsheet using a sample vehicle dataset to demonstrate some of its most useful features.
Sample JSON: vehicles.json
[
{
"id": 1,
"make": "Toyota",
"model": "Camry",
"year": 2020,
"specs": {
"color": "blue",
"engine": "V6",
"features": ["Bluetooth", "Backup Camera"]
}
},
{
"id": 2,
"make": "Honda",
"model": "Civic",
"year": 2018,
"specs": {
"color": "black",
"engine": "I4",
"features": ["Heated Seats"]
}
}
]
jq Commands
Pretty Print
jq '.' vehicles.json
Select a Field
jq '.[].make' vehicles.json
Returns each vehicle make.
Filter by Condition
jq '.[] | select(.year >= 2020)' vehicles.json
Filters vehicles from 2020 or newer.
Field Existence Test
jq '.[] | select(.specs.features != null)' vehicles.json
Only shows vehicles with features listed.
Select Specific Fields
jq '.[] | {make, model}' vehicles.json
Access Nested Fields
jq '.[] | .specs.color' vehicles.json
Combine Fields
jq '.[] | "\(.make) \(.model) - \(.specs.engine)"' vehicles.json
Flatten Arrays
jq '.[] | .specs.features[]' vehicles.json
Group and Count
jq 'group_by(.year) | map({year: .[0].year, count: length})' vehicles.json
Transform Structure
jq 'map({id, fullName: (.make + " " + .model)})' vehicles.json
Delete Fields
jq 'map(del(.specs.features))' vehicles.json
Unique Values
jq '.[].specs.color' vehicles.json | sort | unique
Extracts distinct colors used across all vehicles.
Aggregate
jq '[.[] | .year] | max' vehicles.json
Returns the most recent vehicle year.
Save Filtered Output
jq '.[] | {make, model}' vehicles.json > output.json
Whether you’re filtering for specific fields, flattening arrays, or building new structures, jq
is a must-have tool for any developer working with JSON. Have your own JSON structure? Start experimenting with jq
interactively using tools like jqplay.org.
Leave a Reply