Documentation
¶
Overview ¶
Package yaml implements YAML 1.1/1.2 encoding and decoding for Go programs.
Quick Start ¶
For simple encoding and decoding, use Unmarshal and Marshal:
type Config struct {
Name string `yaml:"name"`
Version string `yaml:"version"`
}
// Decode YAML to Go struct
var config Config
err := yaml.Unmarshal(yamlData, &config)
// Encode Go struct to YAML
data, err := yaml.Marshal(&config)
For encoding/decoding with options, use Load and Dump:
// Decode with strict field checking
err := yaml.Load(data, &config, yaml.WithKnownFields())
// Encode with custom indent
data, err := yaml.Dump(&config, yaml.WithIndent(2))
// Decode all documents from multi-document stream
var docs []Config
err := yaml.Load(multiDocYAML, &docs, yaml.WithAllDocuments())
// Encode multiple documents as multi-document stream
docs := []Config{config1, config2}
data, err := yaml.Dump(docs, yaml.WithAllDocuments())
Streaming with Loader and Dumper ¶
For multi-document streams or when you need custom options, use Loader and Dumper:
// Load multiple documents from a stream
loader, err := yaml.NewLoader(reader)
if err != nil {
log.Fatal(err)
}
for {
var doc any
if err := loader.Load(&doc); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
// Process document...
}
// Dump multiple documents to a stream
dumper, err := yaml.NewDumper(writer, yaml.WithIndent(2))
if err != nil {
log.Fatal(err)
}
dumper.Dump(&doc1)
dumper.Dump(&doc2)
dumper.Close()
Options System ¶
Configure YAML processing behavior with functional options:
yaml.NewDumper(w,
yaml.WithIndent(2), // Indentation spacing
yaml.WithCompactSeqIndent(), // Compact sequences (defaults to true)
yaml.WithLineWidth(80), // Line wrapping width
yaml.WithUnicode(false), // Escape non-ASCII (override default true)
yaml.WithKnownFields(), // Strict field checking (defaults to true)
yaml.WithUniqueKeys(), // Prevent duplicate keys (defaults to true)
yaml.WithSingleDocument(), // Single document mode
)
Or use version-specific option presets for consistent formatting:
yaml.NewDumper(w, yaml.WithV3Defaults())
Options can be combined and later options override earlier ones:
// Start with v3 defaults, then override indent
yaml.NewDumper(w,
yaml.WithV3Defaults(),
yaml.WithIndent(2),
)
Load options from YAML configuration files:
opts, err := yaml.OptsYAML(configYAML) dumper, err := yaml.NewDumper(w, opts)
YAML Compatibility ¶
This package supports most of YAML 1.2, but preserves some YAML 1.1 behavior for backward compatibility:
- YAML 1.1 booleans (yes/no, on/off) are supported when decoding into typed bool values, otherwise treated as strings
- Octals can use 0777 format (YAML 1.1) or 0o777 format (YAML 1.2)
- Base-60 floats are not supported (removed in YAML 1.2)
Version Defaults ¶
NewLoader and NewDumper use v4 defaults (2-space indentation, compact sequences). The older Marshal and Unmarshal functions use v3 defaults for backward compatibility. Use the options system to select different version defaults if needed.
Index ¶
- Constants
- Variables
- func Dump(in any, opts ...Option) (out []byte, err error)
- func Load(in []byte, out any, opts ...Option) error
- func Marshal(in any) (out []byte, err error)
- func Unmarshal(in []byte, out any) (err error)
- type Decoder
- type DepthContext
- type DepthKind
- type DumpError
- type Dumper
- type Encoder
- type Encoding
- type IsZeroer
- type Kind
- type LimitPlugin
- type LineBreak
- type LoadError
- type LoadErrors
- type Loader
- type Mark
- type Marshaler
- type Node
- type Option
- type QuoteStyle
- type Stage
- type Stream
- type Style
- type TagDirective
- type TypeErrordeprecated
- type Unmarshaler
- type VersionDirective
Constants ¶
const ( // DocumentNode represents the root of a YAML document. DocumentNode = libyaml.DocumentNode // SequenceNode represents a YAML sequence (list). SequenceNode = libyaml.SequenceNode // MappingNode represents a YAML mapping (dictionary). MappingNode = libyaml.MappingNode // ScalarNode represents a YAML scalar value. ScalarNode = libyaml.ScalarNode // AliasNode represents a reference to an anchored node. AliasNode = libyaml.AliasNode // StreamNode represents a container for multiple YAML documents. StreamNode = libyaml.StreamNode )
Kind constants define the different types of YAML nodes.
const ( // TaggedStyle explicitly shows the tag on the node. TaggedStyle = libyaml.TaggedStyle // DoubleQuotedStyle uses double quotes for scalar values. DoubleQuotedStyle = libyaml.DoubleQuotedStyle // SingleQuotedStyle uses single quotes for scalar values. SingleQuotedStyle = libyaml.SingleQuotedStyle // LiteralStyle uses literal block scalar style (|). LiteralStyle = libyaml.LiteralStyle // FoldedStyle uses folded block scalar style (>). FoldedStyle = libyaml.FoldedStyle // FlowStyle uses flow style (inline) formatting. FlowStyle = libyaml.FlowStyle )
Style constants define different formatting styles for YAML nodes.
const ( DepthKindFlow = libyaml.DepthKindFlow DepthKindBlock = libyaml.DepthKindBlock )
DepthKind constants for nesting depth checks.
const ( // EncodingAny lets the parser choose the encoding. EncodingAny = libyaml.ANY_ENCODING // EncodingUTF8 is the default UTF-8 encoding. EncodingUTF8 = libyaml.UTF8_ENCODING // EncodingUTF16LE is UTF-16-LE encoding with BOM. EncodingUTF16LE = libyaml.UTF16LE_ENCODING // EncodingUTF16BE is UTF-16-BE encoding with BOM. EncodingUTF16BE = libyaml.UTF16BE_ENCODING )
Encoding constants for YAML stream encoding
const ( // Load stages ReaderStage = libyaml.ReaderStage // Input reading and encoding ScannerStage = libyaml.ScannerStage // Tokenization ParserStage = libyaml.ParserStage // Event stream parsing ComposerStage = libyaml.ComposerStage // Node tree construction ResolverStage = libyaml.ResolverStage // Tag resolution ConstructorStage = libyaml.ConstructorStage // Go value construction // Dump stages RepresenterStage = libyaml.RepresenterStage // Go value to Node tree SerializerStage = libyaml.SerializerStage // Node tree to events EmitterStage = libyaml.EmitterStage // Events to YAML bytes WriterStage = libyaml.WriterStage // Output writing )
Stage constants for YAML processing pipeline.
const ( LineBreakLN = libyaml.LN_BREAK // Unix-style \n (default) LineBreakCR = libyaml.CR_BREAK // Old Mac-style \r LineBreakCRLN = libyaml.CRLN_BREAK // Windows-style \r\n )
Line break constants for different platforms.
const ( QuoteSingle = libyaml.QuoteSingle // Prefer single quotes (v4 default) QuoteDouble = libyaml.QuoteDouble // Prefer double quotes QuoteLegacy = libyaml.QuoteLegacy // Legacy v2/v3 behavior )
Quote style constants for required quoting.
Variables ¶
var ( // WithIndent sets the number of spaces to use for indentation when // dumping YAML content. // // Valid values are 2-9. Common choices: 2 (compact), 4 (readable). WithIndent = libyaml.WithIndent // WithCompactSeqIndent configures whether the sequence indicator '- ' is // considered part of the indentation when dumping YAML content. // // If compact is true, '- ' is treated as part of the indentation. // If compact is false, '- ' is not treated as part of the indentation. // When called without arguments, defaults to true. WithCompactSeqIndent = libyaml.WithCompactSeqIndent // WithKnownFields enables or disables strict field checking during YAML // loading. // // When enabled, loading will return an error if the YAML input contains // fields that do not correspond to any fields in the target struct. // When called without arguments, defaults to true. WithKnownFields = libyaml.WithKnownFields // WithSingleDocument configures the Loader to only process the first // document in a YAML stream. After the first document is loaded, // subsequent calls to Load will return [io.EOF]. // // When called without arguments, defaults to true. // // This is useful when you expect exactly one document and want behavior // similar to Unmarshal. WithSingleDocument = libyaml.WithSingleDocument // WithStreamNodes enables returning stream boundary nodes when loading // YAML. // // When enabled, Loader.Load returns an interleaved sequence of // StreamNode and DocumentNode values: // // [StreamNode, DocNode, StreamNode, DocNode, ..., StreamNode] // // StreamNodes contain metadata about the stream including: // - Encoding (UTF-8, UTF-16LE, UTF-16BE) // - YAML version directive (%YAML) // - Tag directives (%TAG) // - Position information (Line, Column) // // An empty YAML stream returns a single StreamNode. // When called without arguments, defaults to true. // // The default is false. WithStreamNodes = libyaml.WithStreamNodes // WithAllDocuments enables multi-document mode for Load and Dump // operations. // // When used with Load, the target must be a pointer to a slice. // All documents in the YAML stream will be decoded into the slice. // Zero documents results in an empty slice (no error). // // When used with Dump, the input must be a slice. // Each element will be encoded as a separate YAML document // with "---" separators. // // When called without arguments, defaults to true. // // The default is false (single-document mode). WithAllDocuments = libyaml.WithAllDocuments // WithLineWidth sets the preferred line width for YAML output. // // When encoding long strings, the encoder will attempt to wrap them at // this width using literal block style (|). Set to -1 or 0 for unlimited // width. // // The default is 80 characters. WithLineWidth = libyaml.WithLineWidth // WithUnicode controls whether non-ASCII characters are allowed in YAML // output. // // When true, non-ASCII characters appear as-is (e.g., "café"). // When false, non-ASCII characters are escaped (e.g., "caf\u00e9"). // When called without arguments, defaults to true. // // The default is true. WithUnicode = libyaml.WithUnicode // WithUniqueKeys enables or disables duplicate key detection during YAML // loading. // // When enabled, loading will return an error if the YAML input contains // duplicate keys in any mapping. This is a security feature that prevents // key override attacks. // When called without arguments, defaults to true. // // The default is true. WithUniqueKeys = libyaml.WithUniqueKeys // WithCanonical forces canonical YAML output format. // // When enabled, the encoder outputs strictly canonical YAML with explicit // tags for all values. This produces verbose output primarily useful for // debugging and YAML spec compliance testing. // When called without arguments, defaults to true. // // The default is false. WithCanonical = libyaml.WithCanonical // WithLineBreak sets the line ending style for YAML output. // // Available options: // - LineBreakLN: Unix-style \n (default) // - LineBreakCR: Old Mac-style \r // - LineBreakCRLN: Windows-style \r\n // // The default is LineBreakLN. WithLineBreak = libyaml.WithLineBreak // WithExplicitStart controls whether document start markers (---) are // always emitted. // // When true, every document begins with an explicit "---" marker. // When false (default), the marker is omitted for the first document. // When called without arguments, defaults to true. WithExplicitStart = libyaml.WithExplicitStart // WithExplicitEnd controls whether document end markers (...) are always // emitted. // // When true, every document ends with an explicit "..." marker. // When false (default), the marker is omitted. // When called without arguments, defaults to true. WithExplicitEnd = libyaml.WithExplicitEnd // WithFlowSimpleCollections controls whether simple collections use flow // style. // // When true, sequences and mappings containing only scalar values (no // nested collections) are rendered in flow style if they fit within the // line width. // Example: {name: test, count: 42} or [a, b, c] // When called without arguments, defaults to true. // // When false (default), all collections use block style. WithFlowSimpleCollections = libyaml.WithFlowSimpleCollections // WithQuotePreference sets the preferred quote style for strings that // require quoting. // // This option only affects strings that require quoting per the YAML spec. // Plain strings that don't need quoting remain unquoted regardless of this // setting. Quoting is required for: // - Strings that look like other YAML types (true, false, null, 123, etc.) // - Strings with leading/trailing whitespace // - Strings containing special YAML syntax characters // - Empty strings in certain contexts // // Quote styles: // - QuoteSingle: Use single quotes (v4 default) // - QuoteDouble: Use double quotes // - QuoteLegacy: Legacy v2/v3 behavior (mixed quoting) WithQuotePreference = libyaml.WithQuotePreference )
Option configuration functions
var NewDumpError = libyaml.NewDumpError
NewDumpError creates a DumpError with an underlying cause error. The cause is accessible via Unwrap for use with errors.Is and errors.As.
var NewLoadError = libyaml.NewLoadError
NewLoadError creates a LoadError with an underlying cause error. The cause is accessible via Unwrap for use with errors.Is and errors.As.
Functions ¶
func Marshal ¶
Marshal serializes the value provided into a YAML document. The structure of the generated document will reflect the structure of the value itself. Maps and pointers (to struct, string, int, etc) are accepted as the in value.
Struct fields are only marshaled if they are exported (have an upper case first letter), and are marshaled using the field name lowercased as the default key. Custom keys may be defined via the "yaml" name in the field tag: the content preceding the first comma is used as the key, and the following comma-separated options are used to tweak the marshaling process. Conflicting names result in a runtime error.
The field tag format accepted is:
`(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)`
The following flags are currently supported:
omitempty Only include the field if it's not set to the zero
value for the type or to empty slices or maps.
Zero valued structs will be omitted if all their public
fields are zero, unless they implement an IsZero
method (see the IsZeroer interface type), in which
case the field will be excluded if IsZero returns true.
flow Marshal using a flow style (useful for structs,
sequences and maps).
inline Inline the field, which must be a struct or a map,
causing all of its fields or keys to be processed as if
they were part of the outer struct. For maps, keys must
not conflict with the yaml keys of other struct fields.
See doc/inline-tags.md for detailed examples and use cases.
In addition, if the key is "-", the field is ignored.
For example:
type T struct {
F int `yaml:"a,omitempty"`
B int
}
yaml.Marshal(&T{B: 2}) // Returns "b: 2\n"
yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n"
func Unmarshal ¶
Unmarshal decodes the first document found within the in byte slice and assigns decoded values into the out value.
Maps and pointers (to a struct, string, int, etc) are accepted as out values. If an internal pointer within a struct is not initialized, the yaml package will initialize it if necessary for unmarshalling the provided data. The out parameter must not be nil.
The type of the decoded values should be compatible with the respective values in out. If one or more values cannot be decoded due to a type mismatches, decoding continues partially until the end of the YAML content, and a *yaml.LoadErrors is returned with details for all missed values.
Struct fields are only unmarshalled if they are exported (have an upper case first letter), and are unmarshalled using the field name lowercased as the default key. Custom keys may be defined via the "yaml" name in the field tag: the content preceding the first comma is used as the key, and the following comma-separated options are used to tweak the marshaling process (see Marshal). Conflicting names result in a runtime error.
For example:
type T struct {
F int `yaml:"a,omitempty"`
B int
}
var t T
yaml.Construct([]byte("a: 1\nb: 2"), &t)
See the documentation of Marshal for the format of tags and a list of supported tag options.
Types ¶
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
A Decoder reads and decodes YAML values from an input stream.
func NewDecoder ¶
NewDecoder returns a new decoder that reads from r.
The decoder introduces its own buffering and may read data from r beyond the YAML values requested.
func (*Decoder) Decode ¶
Decode reads the next YAML-encoded value from its input and stores it in the value pointed to by v.
See the documentation for Unmarshal for details about the conversion of YAML into a Go value.
func (*Decoder) KnownFields ¶
KnownFields ensures that the keys in decoded mappings to exist as fields in the struct being decoded into.
type DepthContext ¶
type DepthContext = libyaml.DepthContext
DepthContext holds context about a nesting depth check.
type DumpError ¶
DumpError represents an error that occurred while dumping a YAML document.
It identifies the processing stage where the error occurred and provides an optional underlying cause via Unwrap.
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
An Encoder writes YAML values to an output stream.
func NewEncoder ¶
NewEncoder returns a new encoder that writes to w. The Encoder should be closed after use to flush all data to w.
func (*Encoder) Close ¶
Close closes the encoder by writing any remaining data. It does not write a stream terminating string "...".
func (*Encoder) CompactSeqIndent ¶
func (e *Encoder) CompactSeqIndent()
CompactSeqIndent makes it so that '- ' is considered part of the indentation.
func (*Encoder) DefaultSeqIndent ¶
func (e *Encoder) DefaultSeqIndent()
DefaultSeqIndent makes it so that '- ' is not considered part of the indentation.
func (*Encoder) Encode ¶
Encode writes the YAML encoding of v to the stream. If multiple items are encoded to the stream, the second and subsequent document will be preceded with a "---" document separator, but the first will not.
See the documentation for Marshal for details about the conversion of Go values to YAML.
type IsZeroer ¶
IsZeroer is used to check whether an object is zero to determine whether it should be omitted when marshaling with the ,omitempty flag. One notable implementation is time.Time.
type LimitPlugin ¶
type LimitPlugin interface {
// CheckDepth is called when the parser increases nesting depth.
// depth is the current nesting level; ctx.Kind is "flow" or "block".
// Return an error to abort parsing.
CheckDepth(depth int, ctx *DepthContext) error
// CheckAlias is called during alias expansion.
// Return an error to abort construction.
CheckAlias(aliasCount, constructCount int) error
}
LimitPlugin configures safety limits for YAML parsing.
When registered, CheckDepth is called on each nesting depth increase, and CheckAlias is called on each alias expansion to detect excessive aliasing.
Example usage:
import "go.yaml.in/yaml/v4/plugin/limit" loader := yaml.NewLoader(data, yaml.WithPlugin(limit.New(limit.AliasNone())))
type LoadError ¶
LoadError represents an error encountered while decoding a YAML document.
It contains details about the location in the document where the error occurred, as well as the processing stage that generated it.
type LoadErrors ¶
type LoadErrors = libyaml.LoadErrors
LoadErrors is returned when one or more fields cannot be properly decoded.
It contains multiple *LoadError instances with details about each error.
type Marshaler ¶
Marshaler interface may be implemented by types to customize their behavior when being marshaled into a YAML document.
type Node ¶
Node represents an element in the YAML document hierarchy. While documents are typically encoded and decoded into higher level types, such as structs and maps, Node is an intermediate representation that allows detailed control over the content being decoded or encoded.
It's worth noting that although Node offers access into details such as line numbers, columns, and comments, the content when re-encoded will not have its original textual representation preserved. An effort is made to render the data pleasantly, and to preserve comments near the data they describe, though.
Values that make use of the Node type interact with the yaml package in the same way any other type would do, by encoding and decoding yaml data directly or indirectly into them.
For example:
var person struct {
Name string
Address yaml.Node
}
err := yaml.Unmarshal(data, &person)
Or by itself:
var person Node err := yaml.Unmarshal(data, &person)
type Option ¶
Option allows configuring YAML loading and dumping operations.
func Options ¶
Options combines multiple options into a single Option. This is useful for creating option presets or combining version defaults with custom options.
Example:
opts := yaml.Options(yaml.WithV4Defaults(), yaml.WithIndent(3)) yaml.Dump(&data, opts)
func OptsYAML ¶
OptsYAML parses a YAML string containing option settings and returns an Option that can be combined with other options using Options().
The YAML string can specify any of these fields: - indent (int) - compact-seq-indent (bool) - line-width (int) - unicode (bool) - canonical (bool) - line-break (string: ln, cr, crln) - explicit-start (bool) - explicit-end (bool) - flow-simple-coll (bool) - known-fields (bool) - single-document (bool) - unique-keys (bool) - plugin (map of plugin name to config)
The plugin field configures plugins by name. Each key is a plugin name and the value is its configuration map (or null for defaults). Currently supported: "limit" with keys "depth" and "alias" (int or null to disable).
Only fields specified in the YAML will override other options when combined. Unspecified fields won't affect other options.
Example:
opts, err := yaml.OptsYAML(`
indent: 3
known-fields: true
plugin:
limit:
depth: 50
`)
yaml.Dump(&data, yaml.Options(V4, opts))
func WithPlugin ¶
WithPlugin registers one or more plugins for YAML processing.
Plugins extend the YAML library with custom processing logic. Each plugin implements one or more plugin interfaces. Currently supported plugin types:
- LimitPlugin: Controls depth and alias expansion limits
Example:
import "go.yaml.in/yaml/v4/plugin/limit" loader := yaml.NewLoader(data, yaml.WithPlugin(limit.New(limit.AliasNone())))
Plugins use public types and can be implemented by external packages.
func WithV2Defaults ¶
func WithV2Defaults() Option
WithV2Defaults returns V2-compatible default options.
func WithV3Defaults ¶
func WithV3Defaults() Option
WithV3Defaults returns V3-compatible default options.
func WithV4Defaults ¶
func WithV4Defaults() Option
WithV4Defaults returns the current V4 default options.
type QuoteStyle ¶
type QuoteStyle = libyaml.QuoteStyle
QuoteStyle represents the quote style to use when quoting is required.
type Stage ¶
Stage identifies the processing stage where an error occurred during YAML loading or dumping.
type TagDirective ¶
type TagDirective = libyaml.StreamTagDirective
TagDirective represents a YAML %TAG directive for stream nodes.
type TypeError
deprecated
TypeError is a legacy error type retained for compatibility.
Deprecated: Use LoadErrors instead.
type Unmarshaler ¶
type Unmarshaler = libyaml.Unmarshaler
Unmarshaler is the interface implemented by types that can unmarshal a YAML description of themselves.
type VersionDirective ¶
type VersionDirective = libyaml.StreamVersionDirective
Re-export stream-related types
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
go-yaml
command
|
|
|
example
|
|
|
basic_dumper
command
|
|
|
basic_loader
command
|
|
|
dumper_indent_comparison
command
|
|
|
dumper_with_indent
command
|
|
|
load_into_node
command
|
|
|
loader_dumper_demo
command
|
|
|
multi_document_dumper
command
|
|
|
multi_document_loader
command
|
|
|
multiple_options_loader
command
|
|
|
node_dump_with_options
command
|
|
|
node_load_decode_comparison
command
|
|
|
node_load_strict_unmarshaler
command
|
|
|
node_programmatic_build
command
|
|
|
single_document_loader
command
|
|
|
version_options
command
|
|
|
with_v4_option
command
|
|
|
with_v4_override
command
|
|
|
internal
|
|
|
libyaml
Package libyaml contains internal helpers for working with YAML
|
Package libyaml contains internal helpers for working with YAML |
|
testutil/assert
Package assert provides assertion functions for tests.
|
Package assert provides assertion functions for tests. |
|
testutil/datatest
Package datatest provides utilities for data-driven testing with YAML test files.
|
Package datatest provides utilities for data-driven testing with YAML test files. |
|
Package plugin provides official YAML plugins for go-yaml.
|
Package plugin provides official YAML plugins for go-yaml. |
|
limit
Package limit provides a configurable safety limit plugin for go-yaml.
|
Package limit provides a configurable safety limit plugin for go-yaml. |