Skip to content
Latchkey

yq keys and length: Inspect Structure

yq keys returns the keys of a map or indices of an array, and length counts elements, characters, or fields.

Before editing or asserting, you often need to know what is in a document: which keys exist, how many items a list has, whether a field is present. keys, length, and has() answer that.

What it does

keys returns a sorted list of a map's keys (or an array's indices). length returns the element count of an array, the number of keys in a map, or the character count of a string. has("k") returns a boolean for whether a key exists, useful with select and -e.

Common usage

Terminal
yq '.services | keys' compose.yaml
yq '.spec.template.spec.containers | length' deploy.yaml
yq -e '.metadata | has("annotations")' deploy.yaml && echo present

Introspection

ExpressionReturns
keysSorted keys of a map / indices of an array
keys_unsortedKeys in document order
lengthCount of elements, keys, or characters
has("k")Boolean: does key k exist
typeThe node type: !!map, !!seq, !!str, etc.
.. | select(tag == "!!null")Find all null nodes

In CI

Gate a step on structure: yq -e '.spec.replicas >= 1' deploy.yaml fails the job when the assertion is false. Read a count into an output with COUNT=$(yq '.services | length' compose.yaml); echo "count=$COUNT" >> "$GITHUB_OUTPUT".

Common errors in CI

keys or length on a scalar (a string or number) errors with a type message because they expect a map or array; check type first. has() on a null parent returns an error rather than false; guard with .parent != null. Note these functions match jq names, so they also run under Python yq, meaning a passing keys command does not by itself confirm the Go implementation.

Related guides

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