Skip to content
Latchkey

jq length : Count Elements or String Size

jq length returns the number of elements in an array, the key count of an object, or the character length of a string.

A length check is a cheap CI gate: assert an API returned at least one item before a later step tries to use it.

What it does

length is polymorphic: on an array it is the element count, on an object the number of keys, on a string the number of characters, on a number its absolute value, and on null it is 0.

Common usage

Terminal
# how many open PRs?
gh api repos/cli/cli/pulls --jq 'length'
# fail a step if the result is empty
test "$(jq 'length' results.json)" -gt 0 || exit 1
# length of a nested array
jq '.workflows | length' runs.json

Functions

Inputlength returns
arrayNumber of elements
objectNumber of keys
stringNumber of characters
null0
numberAbsolute value

In CI

length is the simplest emptiness gate. Combine it with --exit-status on a select to fail fast, or capture the count into a shell variable to drive a conditional later in the job.

Common errors in CI

"jq: error: boolean (true) has no length" means you called length on a boolean, which is unsupported; coerce or branch first. If length unexpectedly returns 0, the field was null upstream, since null length is defined as 0 rather than an error.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →