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
- Wrap the data in an array: `yq -o csv '[.]'` or `yq -o csv '[.records[]]'`
- Use `map(...)` / `to_entries` to produce an array before encoding
- 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
- Always feed an array to `-o csv`; wrap single objects with `[.]`
- Check the root `type` before choosing CSV output
- Use JSON output when the data is not an array
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
- csv object encoding only works for arrays of flat objects (s
- csv object encoding only works for arrays of flat objects (s
- HCL encoder expects a mapping at the root level, got %v
- failed to encode HCL: %w
- unsupported character %q in raw HCL expression
AI-assisted analysis of mikefarah/yq@8b5af0694b (2026-09-05).
Data as JSON: /api/errors/6352a91a9fe0db5c.
Report an issue: GitHub.