JQ examples / cookbook

Last modified: March 23, 2023

select by attribute value

JQ playground
.servers[] | select(.role == "backend") | .ip

sort by

JQ playground
.countries | sort_by(.population) | reverse | .[] | .name

group by

JQ playground
.calls | group_by(.route) | map({key: .[0].route, value: map(.path)})

group by + count

JQ playground
.calls | group_by(.route) | map({key: .[0].route, value: map(.callTimeMs) | length})

group by + add

JQ playground
.calls | group_by(.route) | map({key: .[0].route, value: map(.callTimeMs) | add})

from entries

JQ playground
.countries[] | [{key:.name, value: {id, population}}] | from_entries

with entries

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

map

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

map values

JQ playground
map_values({name, ageYears: .age})

helper function

JQ playground
def isLocalhost: . == "127.0.0.1";

.hosts[] | {localhost: .host | isLocalhost}

if/else condition

JQ playground
def areaFromCountry: if . == "USA" then "North America"
  elif . == "Germany" then "Europe"
  elif . == "Japan" then "Asia"
  else "Unknown"
  end;

.countries[] | {area: .name | areaFromCountry}