mikefarah/yq · error

csv encoding only works for arrays, got: %v

Error message

csv encoding only works for arrays, got: %v

What it means

The CSV encoder requires the node being encoded to be a sequence (array) at the root — either an array of scalar rows or an array of flat objects. This error is thrown when the top-level node passed to the CSV encoder is a scalar or mapping instead of an array.

Source

Thrown at pkg/yqlib/encoder_csv.go:115

		if err != nil {
			return err
		}

	}
	return nil
}

func (e *csvEncoder) Encode(writer io.Writer, node *CandidateNode) error {
	if node.Kind == ScalarNode {
		return writeString(writer, node.Value+"\n")
	}

	csvWriter := csv.NewWriter(writer)
	csvWriter.Comma = e.separator

	// node must be a sequence
	if node.Kind != SequenceNode {
		return fmt.Errorf("csv encoding only works for arrays, got: %v", node.Tag)
	} else if len(node.Content) == 0 {
		return nil
	}
	if node.Content[0].Kind == ScalarNode {
		return e.encodeRow(csvWriter, node.Content)
	}

	if node.Content[0].Kind == MappingNode {
		return e.encodeObjects(csvWriter, node.Content)
	}

	return e.encodeArrays(csvWriter, node.Content)

}

View on GitHub (pinned to 8b5af0694b)

Solutions

  1. Wrap the data in an array: `yq -o csv '[.]'` or `yq -o csv '[.records[]]'`
  2. Use `map(...)` / `to_entries` to produce an array before encoding
  3. Choose a different output format (JSON/YAML) for non-array data

Example fix

// before: yq -o csv '{a: 1, b: 2}'
// after:  yq -o csv '[{a: 1, b: 2}]'
Defensive patterns

Strategy: validation

Validate before calling

yq 'type == "!!seq"' input.yaml   # must print true before -o csv

Type guard

func isSequence(node *CandidateNode) bool { return node.Kind == SequenceNode }

Try / catch

out, err := encoder.Encode(node)
if err != nil && strings.Contains(err.Error(), "csv encoding only works for arrays") {
    // wrap in array: ctx = singleChildContext(candidate.CreateReplacement(SequenceNode, "!!seq", ...))
}

Prevention

When it happens

Trigger: `yq -o csv '{a: 1}'` (root is a map) or `yq -o csv '"hello"'` (root is a scalar); also wrapping a single object without putting it in an array.

Common situations: Forgetting to wrap a single object with `[...]` or `[]` in the expression; piping `-o csv` onto documents that are maps; users expecting CSV of a single record to work directly.

Related errors


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