mikefarah/yq · error

only arrays are supported for flatten

Error message

only arrays are supported for flatten

What it means

The `flatten` operator collapses nested arrays into a single array. It requires each candidate node to be a SequenceNode; if the node is a map, scalar, or null, the operator aborts with this error. flatten does not descend into or flatten object values, only sequences.

Source

Thrown at pkg/yqlib/operator_flatten.go:43

				newSeq = append(newSeq, content[i].Content[j])
			}
		} else {
			newSeq = append(newSeq, content[i])
		}
	}
	node.Content = make([]*CandidateNode, 0)
	node.AddChildren(newSeq)
}

func flattenOp(_ *dataTreeNavigator, context Context, expressionNode *ExpressionNode) (Context, error) {

	log.Debugf("flatten Operator")
	depth := expressionNode.Operation.Preferences.(flattenPreferences).depth

	for el := context.MatchingNodes.Front(); el != nil; el = el.Next() {
		candidate := el.Value.(*CandidateNode)
		if candidate.Kind != SequenceNode {
			return Context{}, fmt.Errorf("only arrays are supported for flatten")
		}

		flatten(candidate, depth)

	}

	return context, nil

}

View on GitHub (pinned to 8b5af0694b)

Solutions

  1. Select the array first: `.myList | flatten` instead of `flatten` on the root object
  2. Convert object values to a sequence first: `[.[] | arrays] | flatten` or `[.[]] | flatten`
  3. Guard nulls: `.data // [] | flatten`
  4. If you need to flatten values inside objects, explode them with to_entries/toarray first

Example fix

// before
{a: [1, [2]]} | flatten
// error: only arrays are supported for flatten

// after
{a: [1, [2]]} | .a | flatten   # => [1, 2]
Defensive patterns

Strategy: type-guard

Validate before calling

yq 'select(kind == "seq") // empty' input.yaml

Type guard

def as_seq(v):
    return v if isinstance(v, list) else []

Try / catch

out=$(yq '.data // [] | flatten' f.yaml 2>&1) || {
  echo "flatten target is not an array: $out" >&2
}

Prevention

When it happens

Trigger: Running `flatten` on a map (`{a: [1,2]}`), on a scalar, on null, or on a mixed collection where some matched nodes aren't arrays.

Common situations: Applying flatten to the whole document instead of a specific array field; expecting object-of-arrays to be flattened; input from JSON where the top level is an object; empty files producing null nodes.

Related errors


AI-assisted analysis of mikefarah/yq@8b5af0694b (2026-09-05). Data as JSON: /api/errors/3d14dbe0ea180980. Report an issue: GitHub.