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]

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"}

Pipe

select from each element

.car.options[] | .price

Advanced

Filtering JSON objects based on the value of a specific key

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

Sorting JSON objects by key value

.people[] | sort_by(.age)

Grouping JSON objects based on a key value

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

Flattening nested JSON objects

.people[].address[]

Merging multiple JSON objects into one

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

map/to_entries/from_entries/with_entries

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

map_values - similar to map but works well for objects

map_values({name, ageYears: .age})

to_entries - Convert from object to an array of key value paris

//input
{
    "john": "smith",
    "bob": "iger"
}
to_entries
// output
[
    {
      "key": "john",
      "value": "smith"
    },
    {
      "key": "bob",
      "value": "iger"
    }
  ]

from_entries - convert from an array from key/value pairs to an object

//input
[
    {
        "key": "john",
        "value": "smith"
    },
    {
        "key": "bob",
        "value": "iger"
    }
]
//command
from_entries
//output
{
    "john": "smith",
    "bob": "iger"
}

with_entries combines it together

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

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: .age | isOld}