Executable reference

Useful jq, without the scavenger hunt.

Search 43 focused examples by task or syntax. Every recipe includes sample input, exact output, and a one-click path into the workbench.

jq examples

43 examples
Start here

Return the input unchanged

The identity filter is the smallest useful jq program.

.
Input and expected output
Input
{"hello":"world"}
Expected output
{
  "hello": "world"
}
Start here

Read a nested field

Chain object identifiers to walk through nested objects.

.user.profile.name
Input and expected output
Input
{"user":{"profile":{"name":"Ada"}}}
Expected output
"Ada"
Start here

Read a key with punctuation

Use bracket notation when a key is not a valid jq identifier.

.["first-name"]
Input and expected output
Input
{"first-name":"Ada"}
Expected output
"Ada"
Start here

Ignore a missing optional field

The optional operator suppresses an error when the input cannot be indexed.

.users[] | .profile?.email?
Input and expected output
Input
{"users":[{"profile":{"email":"a@example.test"}},null]}
Expected output
"a@example.test"
null

A missing object field normally yields null; ? is most useful when the input type may differ.

Start here

Emit every array item

.[] is a generator: one input can produce many output values.

.users[]
Input and expected output
Input
{"users":["Ada","Grace","Linus"]}
Expected output
"Ada"
"Grace"
"Linus"
Start here

Pick an array item

Array indexes are zero-based; negative indexes count from the end.

.users[-1]
Input and expected output
Input
{"users":["Ada","Grace","Linus"]}
Expected output
"Linus"
Start here

Take an array slice

A slice includes the start index and excludes the end index.

.[1:4]
Input and expected output
Input
[0,1,2,3,4]
Expected output
[
  1,
  2,
  3
]
Start here

Compose filters with a pipe

The right side runs once for every value emitted on the left.

.users[] | .name
Input and expected output
Input
{"users":[{"name":"Ada"},{"name":"Grace"}]}
Expected output
"Ada"
"Grace"
Start here

Emit more than one result

The comma operator sends both filters the same input.

.id, .name
Input and expected output
Input
{"id":42,"name":"Ada"}
Expected output
42
"Ada"
Start here

Collect a stream into an array

Array construction collects all emitted values into one array.

[.users[].name]
Input and expected output
Input
{"users":[{"name":"Ada"},{"name":"Grace"}]}
Expected output
[
  "Ada",
  "Grace"
]
Select & transform

Keep matching objects

select emits its input only when the condition is truthy.

.users[] | select(.active)
Input and expected output
Input
{"users":[{"name":"Ada","active":true},{"name":"Linus","active":false}]}
Expected output
{
  "name": "Ada",
  "active": true
}
Select & transform

Transform every array item

map applies a filter to each item and collects the results.

.prices | map(. * 1.2)
Input and expected output
Input
{"prices":[10,25,40]}
Expected output
[
  12,
  30,
  48
]
Select & transform

Transform every object value

map_values updates values while retaining their keys.

.stock | map_values(. + 1)
Input and expected output
Input
{"stock":{"apples":2,"pears":4}}
Expected output
{
  "apples": 3,
  "pears": 5
}
Select & transform

Check whether a key exists

has distinguishes an absent key from a key whose value is null.

has("email")
Input and expected output
Input
{"name":"Ada","email":null}
Expected output
true
Select & transform

Check whether a value is contained

contains recursively tests whether the input contains another value.

contains({"roles":["admin"]})
Input and expected output
Input
{"name":"Ada","roles":["admin","editor"]}
Expected output
true
Construct values

Reshape an object

Build a new object and use shorthand when the key and field name match.

{id, displayName: .profile.name}
Input and expected output
Input
{"id":7,"profile":{"name":"Ada"},"private":true}
Expected output
{
  "id": 7,
  "displayName": "Ada"
}
Construct values

Create a computed object key

Put an expression in parentheses to compute an object key.

{(.key): .value}
Input and expected output
Input
{"key":"status","value":"ready"}
Expected output
{
  "status": "ready"
}
Construct values

Interpolate values into a string

\(filter) inserts a filter result into a jq string.

.users[] | "\(.name): \(.role)"
Input and expected output
Input
{"users":[{"name":"Ada","role":"admin"}]}
Expected output
"Ada: admin"
Construct values

Update nested data

|= feeds the current value through a filter and writes the result back.

.users |= map(. + {active: true})
Input and expected output
Input
{"users":[{"name":"Ada"},{"name":"Grace"}]}
Expected output
{
  "users": [
    {
      "name": "Ada",
      "active": true
    },
    {
      "name": "Grace",
      "active": true
    }
  ]
}
Types & defaults

Provide a fallback value

// returns the right side when the left produces false, null, or no value.

.nickname // "Anonymous"
Input and expected output
Input
{"name":"Ada","nickname":null}
Expected output
"Anonymous"

Boolean false also activates the fallback.

Types & defaults

Inspect value types

type reports jq types such as object, array, number, and string.

map(type)
Input and expected output
Input
[null,true,12,"jq",[],{}]
Expected output
[
  "null",
  "boolean",
  "number",
  "string",
  "array",
  "object"
]
Types & defaults

List object keys

keys returns sorted object keys; keys_unsorted keeps approximate insertion order.

keys
Input and expected output
Input
{"z":1,"a":2,"m":3}
Expected output
[
  "a",
  "m",
  "z"
]
Types & defaults

Rename every object key

with_entries exposes each property as {key, value}, then rebuilds the object.

with_entries(.key |= ascii_downcase)
Input and expected output
Input
{"FirstName":"Ada","ROLE":"Admin"}
Expected output
{
  "firstname": "Ada",
  "role": "Admin"
}
Types & defaults

Remove sensitive fields

del removes one or more paths from a copied result.

del(.password, .token)
Input and expected output
Input
{"name":"Ada","password":"secret","token":"abc"}
Expected output
{
  "name": "Ada"
}
Sort & aggregate

Sort objects by a field

sort_by evaluates a key expression for every array item.

sort_by(.score) | reverse
Input and expected output
Input
[{"name":"Ada","score":92},{"name":"Grace","score":98},{"name":"Linus","score":85}]
Expected output
[
  {
    "name": "Grace",
    "score": 98
  },
  {
    "name": "Ada",
    "score": 92
  },
  {
    "name": "Linus",
    "score": 85
  }
]
Sort & aggregate

Group items by a field

group_by sorts values by the key and collects equal keys together.

group_by(.team) | map({team: .[0].team, members: map(.name)})
Input and expected output
Input
[{"name":"Ada","team":"compiler"},{"name":"Grace","team":"compiler"},{"name":"Linus","team":"kernel"}]
Expected output
[
  {
    "team": "compiler",
    "members": [
      "Ada",
      "Grace"
    ]
  },
  {
    "team": "kernel",
    "members": [
      "Linus"
    ]
  }
]
Sort & aggregate

Deduplicate by a field

unique_by keeps one value for each distinct key and sorts by that key.

unique_by(.id)
Input and expected output
Input
[{"id":2,"name":"Grace"},{"id":1,"name":"Ada"},{"id":2,"name":"Duplicate"}]
Expected output
[
  {
    "id": 1,
    "name": "Ada"
  },
  {
    "id": 2,
    "name": "Grace"
  }
]
Sort & aggregate

Sum an array of numbers

add reduces an array using jq addition.

.orders | map(.total) | add
Input and expected output
Input
{"orders":[{"total":12.5},{"total":7.5},{"total":20}]}
Expected output
40
Sort & aggregate

Find the maximum by a field

max_by returns the item whose key expression is greatest.

max_by(.score)
Input and expected output
Input
[{"name":"Ada","score":92},{"name":"Grace","score":98}]
Expected output
{
  "name": "Grace",
  "score": 98
}
Strings & regex

Split and join text

split creates an array; join combines its values with a separator.

.path | split("/") | map(ascii_upcase) | join(" › ")
Input and expected output
Input
{"path":"docs/guides/jq"}
Expected output
"DOCS › GUIDES › JQ"
Strings & regex

Test a regular expression

test returns a boolean and accepts optional regex flags.

.users[] | select(.email | test("@example\.com$"; "i")) | .name
Input and expected output
Input
{"users":[{"name":"Ada","email":"ada@EXAMPLE.com"},{"name":"Grace","email":"grace@test.dev"}]}
Expected output
"Ada"
Strings & regex

Capture named regex groups

capture returns an object whose keys are the named groups.

capture("(?<major>[0-9]+)\.(?<minor>[0-9]+)")
Input and expected output
Input
"version 1.8"
Expected output
{
  "major": "1",
  "minor": "8"
}
Strings & regex

Replace every text match

gsub replaces all non-overlapping regex matches.

gsub("[^a-zA-Z0-9]+"; "-") | ascii_downcase
Input and expected output
Input
"Hello, jq world!"
Expected output
"hello-jq-world-"
Control & advanced

Bind a value to a variable

as binds a value while letting the remaining pipeline keep its original input.

. as $root | .users[] | {name, team: $root.team}
Input and expected output
Input
{"team":"compiler","users":[{"name":"Ada"},{"name":"Grace"}]}
Expected output
{
  "name": "Ada",
  "team": "compiler"
}
{
  "name": "Grace",
  "team": "compiler"
}
Control & advanced

Choose a value with if/then/else

Conditions are filters and must end with end.

if .score >= 90 then "excellent" elif .score >= 70 then "pass" else "retry" end
Input and expected output
Input
{"score":84}
Expected output
"pass"
Control & advanced

Recover from an error

try/catch turns an error into a value you can handle deliberately.

try (.value | tonumber) catch "not a number"
Input and expected output
Input
{"value":"unknown"}
Expected output
"not a number"
Control & advanced

List paths to scalar values

paths emits path arrays; scalars limits them to leaf-like values.

[paths(scalars)]
Input and expected output
Input
{"user":{"name":"Ada","active":true},"count":2}
Expected output
[
  [
    "user",
    "name"
  ],
  [
    "user",
    "active"
  ],
  [
    "count"
  ]
]
Control & advanced

Find matching fields recursively

.. walks every descendant; objects selects only values that can have a name field.

.. | objects | .name? // empty
Input and expected output
Input
{"name":"root","children":[{"name":"first"},{"nested":{"name":"second"}}]}
Expected output
"root"
"first"
"second"
Control & advanced

Build an index with reduce

reduce folds a stream into a single accumulated value.

reduce .users[] as $user ({}; .[$user.id] = $user.name)
Input and expected output
Input
{"users":[{"id":"u1","name":"Ada"},{"id":"u2","name":"Grace"}]}
Expected output
{
  "u1": "Ada",
  "u2": "Grace"
}
Formatting & modes

Export rows as CSV

@csv safely quotes array values as a CSV row; raw output removes jq string quotes.

.users[] | [.id, .name, .email] | @csv
Input and expected output
Input
{"users":[{"id":1,"name":"Ada","email":"ada@example.test"},{"id":2,"name":"Grace, G.","email":"grace@example.test"}]}
Expected output
1,"Ada","ada@example.test"
2,"Grace, G.","grace@example.test"
Formatting & modes

Transform a whole text input

Raw whole-text mode passes the editor contents as one jq string.

split("\n") | map(select(length > 0)) | length
Input and expected output
Input
alpha
beta
gamma
Expected output
3
Formatting & modes

Generate data without input

Null-input mode runs the filter once with null and ignores the input editor.

[range(1; 6) | {id: ., square: (. * .)}]
Input and expected output
Input
(ignored)
Expected output
[
  {
    "id": 1,
    "square": 1
  },
  {
    "id": 2,
    "square": 4
  },
  {
    "id": 3,
    "square": 9
  },
  {
    "id": 4,
    "square": 16
  },
  {
    "id": 5,
    "square": 25
  }
]
Formatting & modes

Produce compact, sorted JSON

Compact output writes one JSON value per line; sorted keys make object order predictable.

.
Input and expected output
Input
{"z":1,"a":{"y":2,"b":3}}
Expected output
{"a":{"b":3,"y":2},"z":1}