mikefarah/yq · error

cannot trim %v, can only operate on strings.

Error message

cannot trim %v, can only operate on strings. 

What it means

trim_space (and the ltrimstr/rtrimstr family) requires string input: the guard checks each matched node's resolved tag via guessTagFromCustomType and rejects anything that is not !!str (custom string-like tags are unwrapped first). The node's actual tag replaces the trailing %v in the message.

Source

Thrown at pkg/yqlib/operator_strings.go:147

		candidate := el.Value.(*CandidateNode)
		value, err := interpolate(d, context.SingleChildContext(candidate), expressionNode.Operation.StringValue)
		if err != nil {
			return Context{}, err
		}
		node := createScalarNode(value, value)
		results.PushBack(node)
	}

	return context.ChildContext(results), nil
}

func trimSpaceOperator(_ *dataTreeNavigator, context Context, _ *ExpressionNode) (Context, error) {
	results := list.New()
	for el := context.MatchingNodes.Front(); el != nil; el = el.Next() {
		node := el.Value.(*CandidateNode)

		if node.guessTagFromCustomType() != "!!str" {
			return Context{}, fmt.Errorf("cannot trim %v, can only operate on strings. ", node.Tag)
		}

		newStringNode := node.CreateReplacement(ScalarNode, node.Tag, strings.TrimSpace(node.Value))
		newStringNode.Style = node.Style
		results.PushBack(newStringNode)

	}

	return context.ChildContext(results), nil
}

func toStringOperator(_ *dataTreeNavigator, context Context, _ *ExpressionNode) (Context, error) {
	results := list.New()
	for el := context.MatchingNodes.Front(); el != nil; el = el.Next() {
		node := el.Value.(*CandidateNode)
		var newStringNode *CandidateNode
		if node.Tag == "!!str" {
			newStringNode = node.CreateReplacement(ScalarNode, "!!str", node.Value)

View on GitHub (pinned to 8b5af0694b)

Solutions

  1. Convert first: . | tostring | trim
  2. Select the string field rather than a number/map
  3. Check the value is not null or boolean before trimming
Defensive patterns

Strategy: type-guard

When it happens

Trigger: Thrown at pkg/yqlib/operator_strings.go:147 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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