Cheatsheet: JQ

Basic operations

Identity operator (.)

.

Object identifier/index

.name
.address.city

Generic object index

.["name"]
.address["postal-code"]
.["address"]["postal-code"]

Array operations

Array index

.car.options[1]
.[1]

Array/string slice

.[10:]
.[10:15]
.[:15]

Array length

.car.options | length

Object construction

Select fields without renaming

.{make, model}
.car | {make, model}

Select fields with renaming

.{carMake: .make, carModel: .model}
// {"carMake":"mini cooper","carModel":"countryman"}

Concatenate fields

{car: (.make + " " + .model)}
{car: (.make + " wroom!")}

Value as field name

.{(.make): .model}
// {"mini cooper":"countryman"}

Filtering and transforms

Filter objects by key value

.people[] | select(.age > 30)

Sort an array by key value

.people | sort_by(.age)

Group by key value (sort first)

.people
| sort_by(.gender)
| group_by(.gender)
| map({gender: .[0].gender, names: map(.name)})

Flatten nested arrays

.people | map(.address[])

Merge multiple objects with slurp

jq -s 'reduce .[] as $item ({}; . * $item)'

map/to_entries/from_entries/with_entries

map - transform each array item

.countries | map({name, id, people: .population})

map_values - similar to map for object values

map_values({name, ageYears: .age})

to_entries - object to array of key/value pairs

{
  "john": "smith",
  "bob": "iger"
}
| to_entries

from_entries - key/value pairs to object

[
  {"key":"john","value":"smith"},
  {"key":"bob","value":"iger"}
]
| from_entries

with_entries - edit keys/values inline

with_entries(.key |= ("0" + .))

CLI and safety patterns

Raw output (no JSON quotes)

jq -r '.name' input.json

Fallback/default value

.email // "unknown@example.com"

Optional chaining style access

.user?.profile?.email // "n/a"

Pass a string argument

jq --arg name "Alice" '.name = $name' input.json

Pass a JSON argument

jq --argjson cfg '{"env":"prod"}' '.config = $cfg' input.json

if/else and helper functions

if/else

if .age > 30 then "old" else "young" end

if/elif/else

if .age > 30 then "old" elif .age > 20 then "middle" else "young" end

Helper functions

def isOld: .age > 30;
{old: (. | isOld)}

See also: