jq Examples — Practical jq Query Snippets

Practical, runnable jq snippets. Click any example to open it in the interactive jq playground, then edit the JSON input and the expression to see results instantly.

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

Use jq select() to filter an array of JSON objects by an attribute value. Interactive example that keeps only objects whose field matches a given value.

Open in jq playground
.countries | sort_by(.population) | reverse | .[] | .name

Sort a JSON array by a field using jq sort_by(). Interactive example showing how to sort objects ascending, then reverse for descending order.

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

Group an array of JSON objects by a field with jq group_by(). Interactive example that buckets records by a shared key and collects their values.

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

Count items per group in jq by combining group_by() with length. Interactive example that counts how many records fall into each group.

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

Sum a numeric field per group in jq by combining group_by() with add. Interactive example that totals values within each group.

Open in jq playground
to_entries

Convert a JSON object into an array of {key, value} pairs with jq to_entries. Interactive example for iterating over objects with dynamic keys.

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

Build a JSON object from an array of {key, value} pairs with jq from_entries. Interactive example that rebuilds an object keyed by a chosen field.

Open in jq playground
with_entries(.key |= ("0"+.))

Transform every key or value of a JSON object with jq with_entries. Interactive example that rewrites object keys in a single pass.

Open in jq playground
.countries | map({name, id, people: .population})

Transform each element of a JSON array with jq map(). Interactive example that reshapes and renames fields for every object in an array.

Open in jq playground
map_values({name, ageYears: .age})

Transform every value of a JSON object with jq map_values(). Interactive example that reshapes each value while preserving the object keys.

Open in jq playground
def isLocalhost: . == "127.0.0.1";

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

Define reusable helper functions in jq with def. Interactive example showing how to declare a function and apply it inside a pipeline.

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

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

Branch on values in jq with if / elif / else / end. Interactive example that maps input values to different results using conditional logic.

Open in jq playground