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
yq '.services | keys' compose.yaml
yq '.spec.template.spec.containers | length' deploy.yaml
yq -e '.metadata | has("annotations")' deploy.yaml && echo presentIntrospection
| Expression | Returns |
|---|---|
| keys | Sorted keys of a map / indices of an array |
| keys_unsorted | Keys in document order |
| length | Count of elements, keys, or characters |
| has("k") | Boolean: does key k exist |
| type | The 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.