yaml

package module
v4.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 10 Imported by: 376

README

go-yaml v4

YAML for Go, with the control your application needs.

v4.0.0 is the stable release.

Read YAML into Go values, work with nodes and comments, and write YAML with explicit control over formatting and behavior. Use the same processing pipeline from Go or from the go-yaml command. Maintained by the YAML organization.

Get started · CLI · Options · Plugins · Documentation · Migration

Choose your version

v2 and v3 remain stable. Their APIs are frozen, and their branches receive security fixes only. New features and routine bug fixes are developed in v4.

Version Import path Status
v2 go.yaml.in/yaml/v2 Stable, frozen API; security fixes only
v3 go.yaml.in/yaml/v3 Stable, frozen API; security fixes only
v4 go.yaml.in/yaml/v4 Stable; active development

v4 is designed to be highly compatible with v3. The classic Unmarshal, Marshal, NewDecoder, and NewEncoder entry points remain available. The new Load and Dump APIs add options, plugins, and clearer configuration. Version presets restore v3 defaults, with individual options for finer control. See the migration guide for formatting, error handling, and custom unmarshaler details before upgrading.

Get started

go get go.yaml.in/yaml/v4

Load into structs, maps, slices, or your own types. Export struct fields and use yaml tags to control their names:

package main

import (
    "fmt"
    "log"

    "go.yaml.in/yaml/v4"
)

type Config struct {
    Name string `yaml:"name"`
    Port int    `yaml:"port"`
}

func main() {
    input := []byte("name: api\nport: 8080\n")
    var config Config
    if err := yaml.Load(input, &config, yaml.WithKnownFields()); err != nil {
        log.Fatal(err)
    }

    output, err := yaml.Dump(config, yaml.WithIndent(4))
    if err != nil {
        log.Fatal(err)
    }
    fmt.Print(string(output))
}

Output:

name: api
port: 8080

Use NewLoader and NewDumper for streams and yaml.Node when you need access to tags, styles, anchors, comments, or source positions. Both constructors return an error; check it before using the stream. See the runnable examples and API reference.

The go-yaml CLI

See what YAML is doing at every stage. The CLI exposes the library's scanner, parser, node tree, and output formats. Use it to inspect configuration, explore options, compare behavior, and make bug reports reproducible.

go install go.yaml.in/yaml/v4/cmd/go-yaml@latest

Use this config.yaml:

# Service configuration
service:
  name: api
  port: 8080

Try the same commands with your own file:

go-yaml -J config.yaml
go-yaml -n config.yaml
go-yaml -Y -o indent=4 config.yaml
go-yaml -t config.yaml | go-yaml -e | go-yaml -N | go-yaml -Y
Output Flags What you can inspect
YAML -y / -Y Ordinary encoding / node-aware styles and comments
JSON -j / -J Compact / pretty-printed JSON
Tokens -t / -T Scanner tokens / tokens with source positions
Events -e / -E Parser events / events with source positions
Nodes -n / -N Compact tree / tags and styles included

Select an output mode and pass a file, or pipe input on standard input. Put flags before the file name. Token, event, and node output can be piped into later stages, as shown above. Use -f yaml to force YAML input when a document resembles an intermediate stage's representation. Backward stage conversions are rejected.

The CLI also supports:

  • Options: -o indent=4, repeated -o flags, and presets such as -o v3. Run go-yaml -o help to discover available settings.
  • Configuration: -C options.yaml loads a reusable options file. Command-line -o settings override its individual non-plugin options.
  • Plugins: --plugin selects implementations linked into the executable. Build the optional reference parser with make cli PLUGIN=.... Use PLUGIN-PACKAGE=package@version to link other released implementations, or make cli CONFIG=options.yaml to embed configuration. See plugin builds for complete commands.
  • Layout: -l selects block layout for stage representations.
  • Classic APIs: --unmarshal, --decode, --marshal, and --encode help compare classic library paths with the default Load/Dump pipeline.

Node-aware YAML output retains supported styles and comments; it does not promise byte-for-byte formatting preservation. See the CLI guide for pipelines, plugin builds, configuration, and processing-mode restrictions. The demo source and recording instructions are included.

Options that fit your application

Choose strict loading, indentation, sequence layout, line width, document markers, Unicode handling, and more without wrapping or forking the library. Options work with package functions, streaming loaders and dumpers, and node methods.

err := yaml.Load(input, &config,
    yaml.WithKnownFields(),
    yaml.WithUniqueKeys(),
)

yaml.Load rejects additional documents by default. Use yaml.NewLoader to process a stream one document at a time.

Start from a version preset and override only what you need. Options are applied in order:

output, err := yaml.Dump(config,
    yaml.WithV3Defaults(),
    yaml.WithIndent(2),
)

Load and Dump use v4 defaults: two-space indentation and compact sequences. The classic APIs retain their compatibility settings. To match Marshal formatting when switching to Dump, use WithV3Defaults() followed by WithLineWidth(-1). Presets select defaults; they do not reverse every v4 bug fix or API change.

You can also share configuration between Go code and the CLI:

indent: 4
compact-seq-indent: false
line-width: 100

In Go, parse that YAML with yaml.OptsYAML, check the returned error, and pass the resulting option to Load, Dump, or a stream constructor. On the command line, use go-yaml -Y -C options.yaml config.yaml.

See the options guide for the full reference and presets.

Plugins extend go-yaml's capabilities

go-yaml's plugin APIs let you adapt YAML processing to your application. Use the supplied implementations or implement the public interfaces in your own Go package.

These are the current plugin APIs:

Plugin API Purpose Supplied implementations
loader-limits Control nesting and alias limits Core loader-limits plugin
alias-data Control anchor sources and scope Core alias-data plugin
merge-key Control YAML merge keys and mapping conflicts Core merge-key plugin
error-format Choose how structured errors are presented Core v3 and v4 formatters
yaml-parser Replace the parser behind the node pipeline Built-in Go parser; optional reference parser module
tab-indent Enable and configure tab-indented input Core opt-in tab-indent plugin

For example, set a nesting-depth limit directly in Go:

import (
    "go.yaml.in/yaml/v4"
    "go.yaml.in/yaml/v4/plugin/loaderlimits"
)

// Inside your loading function:
err := yaml.Load(input, &config,
    yaml.WithPlugin(loaderlimits.New(loaderlimits.DepthValue(50))),
)

The core module includes the built-in parser, loader limits, merge-key and alias-data policies, error formatters, and tab-indentation support. JSON-comments and reference-parser implementations are separate modules, so applications acquire those dependencies only when they choose them.

Plugins can be passed directly with WithPlugin or registered by name for YAML configuration. The CLI selects already-linked implementations at runtime; it does not download plugins. See the plugin guide for interfaces, registration, configuration, dependencies, and limitations of each processing path.

Documentation

Start here Learn how to
API reference Use Go types, functions, and interfaces
v3 to v4 migration Upgrade while preserving compatibility
Options guide Control loading and output
Plugin guide Configure or write extensions
CLI guide Inspect stages and build custom commands
Examples Run complete Go programs
Contributor guide Build, test, and contribute

Compatibility

Custom UnmarshalYAML(*yaml.Node) error hooks depend on the exact package that defines Node. Update those hooks and their imports when moving from v3 to v4. V4 reports a migration error for recognized v3 node hooks; the legacy UnmarshalYAML(func(any) error) error callback remains supported across versions. See the migration guide for details.

The library supports most of YAML 1.2 and retains selected YAML 1.1 behavior for compatibility, including legacy octal notation and yes/no booleans when loading into typed Go bools. Consult the API reference and test behavior against your application's data.

Report bugs and propose ideas

Please use the CLI when reporting bugs or suggesting behavior. A small example that others can run helps us understand both failures and proposals. Include:

  1. Minimal input as text and the exact command or Go program you ran.
  2. Actual output and expected output, including errors.
  3. Relevant options, configuration, and plugin selections.
  4. Your Go version, operating system, and installed module revision.

For CLI reports, useful commands include:

go-yaml -T config.yaml
go-yaml -E config.yaml
go-yaml -N config.yaml
go version
go version -m "$(command -v go-yaml)"

If the problem involves Go types, struct tags, or custom marshalers, include a small Go reproducer as well. For ideas, show the input and output you would like the CLI to support. Open an issue or join the maintainers on Slack.

Contributors can build the CLI with make cli, run make test, and enter the project's managed development environment with make shell. The Makefile installs its tools under .cache/. See CONTRIBUTING.md for the full workflow.

Acknowledgments and license

This project builds on the original go-yaml repository by Gustavo Niemeyer and its contributors. It began at Canonical as part of Juju, using a Go port of Kirill Simonov's libyaml. The YAML organization continues its maintenance and development.

See LICENSE and NOTICE. The libyaml-derived files listed in NOTICE retain their original MIT license; the remaining project files are covered by Apache License 2.0.

Documentation

Overview

Package yaml implements YAML 1.1/1.2 encoding and decoding for Go programs.

Quick Start

For new code, use Load and Dump:

type Config struct {
    Name    string `yaml:"name"`
    Version string `yaml:"version"`
}

// Decode YAML to Go struct
var config Config
err := yaml.Load(yamlData, &config)

// Encode Go struct to YAML
data, err := yaml.Dump(&config)

Add options to configure loading and dumping:

// 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)
)

Loading options configure construction rather than output formatting:

yaml.NewLoader(r,
    yaml.WithKnownFields(), // Reject unknown fields (off by default)
    yaml.WithUniqueKeys(),  // Reject duplicate keys (on by default)
)

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)
if err != nil {
    log.Fatal(err)
}
dumper, err := yaml.NewDumper(w, opts)
if err != nil {
    log.Fatal(err)
}

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; Marshal also disables line wrapping. NewEncoder uses v3 output settings with v4 error formatting. Classic APIs remain supported. Use the options system to select different version defaults if needed.

Index

Constants

View Source
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 Node.

View Source
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.

View Source
const (
	IndentModeAuto = libyaml.IndentModeAuto
	IndentModeTabs = libyaml.IndentModeTabs
)
View Source
const (
	IndentStyleAuto   = libyaml.IndentStyleAuto
	IndentStyleSpaces = libyaml.IndentStyleSpaces
	IndentStyleTabs   = libyaml.IndentStyleTabs
)
View Source
const (
	IndentScopeDocument = libyaml.IndentScopeDocument
	IndentScopeStream   = libyaml.IndentScopeStream
)
View Source
const (
	// DepthKindFlow represents flow-style nesting (inside [] or {}).
	DepthKindFlow = libyaml.DepthKindFlow

	// DepthKindBlock represents block-style nesting (inside indentation).
	DepthKindBlock = libyaml.DepthKindBlock
)

DepthKind constants for nesting depth checks

They are the possible values for DepthContext when checking the nesting depth of YAML nodes.

View Source
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

View Source
const (
	// ReaderStage is the input reading and encoding stage.
	ReaderStage = libyaml.ReaderStage
	// ScannerStage is the tokenization stage.
	ScannerStage = libyaml.ScannerStage
	// ParserStage is the event stream parsing stage.
	ParserStage = libyaml.ParserStage
	// ComposerStage is the node tree construction stage.
	ComposerStage = libyaml.ComposerStage
	// ResolverStage is the tag resolution stage.
	ResolverStage = libyaml.ResolverStage
	// ConstructorStage is the Go value construction stage.
	ConstructorStage = libyaml.ConstructorStage
)

Stage constants for YAML loading stages

View Source
const (
	// RepresenterStage is the Go value to Node tree stage.
	RepresenterStage = libyaml.RepresenterStage
	// SerializerStage is the Node tree to event stage.
	SerializerStage = libyaml.SerializerStage
	// EmitterStage is the events to YAML bytes stage.
	EmitterStage = libyaml.EmitterStage
	// WriterStage is the output writing stage.
	WriterStage = libyaml.WriterStage
)

Stage constants for YAML dumping stages

View Source
const (

	// LineBreakLN represents Unix-style line endings (\n), this is the default.
	LineBreakLN = libyaml.LN_BREAK

	// LineBreakCR represents Old Mac-style line endings (\r).
	LineBreakCR = libyaml.CR_BREAK

	// LineBreakCRLN represents Windows-style line endings (\r\n).
	LineBreakCRLN = libyaml.CRLN_BREAK
)

LineBreak constants for different platforms.

View Source
const (
	// QuoteSingle prefers single quotes (v4 default).
	QuoteSingle = libyaml.QuoteSingle

	// QuoteDouble prefers double quotes.
	QuoteDouble = libyaml.QuoteDouble

	// QuoteLegacy uses legacy v2/v3 behavior (mixed quoting).
	QuoteLegacy = libyaml.QuoteLegacy
)

QuoteStyle constants for required quoting.

Variables

View Source
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.
	// Calling WithKnownFields() enables checking; it is disabled by default.
	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 ignores later documents, including their syntax errors.
	// Omit this option with [Load] to require exactly one document.
	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.
	//
	// The emitter attempts to wrap long scalars without changing their value.
	// Long words may exceed this width.
	// 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\xE9").
	// 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 selects the emitter's canonical YAML layout.
	//
	// It emits explicit document starts, flow collections, and quoted scalars.
	// Tags still depend on the node graph and desolver; this option alone does
	// not force an explicit tag on every value.
	// Scalar types may change when reloading canonical output.
	// 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

View Source
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.

View Source
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 Dump

func Dump(in any, opts ...Option) (out []byte, err error)

Dump encodes a value to YAML with the given options.

By default, Dump encodes a single value as a single YAML document.

Use WithAllDocuments to encode multiple values as a multi-document stream:

docs := []Config{config1, config2, config3}
yaml.Dump(docs, yaml.WithAllDocuments())

When WithAllDocuments is used, in must be a slice. Each element is encoded as a separate YAML document with "---" separators.

See Marshal for details.

func Load

func Load(in []byte, out any, opts ...Option) error

Load loads YAML document(s) with the given options.

By default, Load requires exactly one document in the input. If zero documents are found, it returns an error. If multiple documents are found, it returns an error.

Use WithAllDocuments to load all documents into a slice:

var configs []Config
yaml.Load(multiDocYAML, &configs, yaml.WithAllDocuments())

When WithAllDocuments is used, out must be a pointer to a slice. Each document is loaded into the slice element type. Zero documents results in an empty slice (no error).

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.

The out parameter must not be nil.

The type of the loaded values should be compatible with the respective values in out.

If one or more values cannot be loaded due to 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 loaded if they are exported (have an upper case first letter), and are loaded 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 control the loading and dumping behavior.

For example:

type T struct {
    F int `yaml:"a,omitempty"`
    B int
}
var t T
yaml.Load([]byte("a: 1\nb: 2"), &t)

See the documentation of Dump for the format of tags and a list of supported tag options.

func Marshal

func Marshal(in any) (out []byte, err error)

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.

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 RegisterPlugin

func RegisterPlugin(registration PluginRegistration) error

RegisterPlugin registers a named implementation for OptsYAML and WithNamedPlugin. Register during application startup, before parsing configuration. Duplicate API and implementation name pairs are errors.

func Unmarshal

func Unmarshal(in []byte, out any) (err error)

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.Unmarshal([]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 AliasDataContext

type AliasDataContext = libyaml.AliasDataContext

AliasDataContext owns node-based anchor storage and alias lookup.

type AliasDataPlugin

type AliasDataPlugin = libyaml.AliasDataPlugin

AliasDataPlugin creates per-stream anchor and alias policies.

type AliasDataServices

type AliasDataServices = libyaml.AliasDataServices

AliasDataServices supplies source snapshots and node conversions.

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

A Decoder reads and decodes YAML values from an input stream.

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

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

func (dec *Decoder) Decode(v any) error

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

func (dec *Decoder) KnownFields(enable bool)

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 DepthKind

type DepthKind = libyaml.DepthKind

DepthKind represents the type of nesting (flow or block).

type DumpError

type DumpError = libyaml.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 Dumper

type Dumper struct {
	// contains filtered or unexported fields
}

Dumper writes YAML values to an output stream with configurable options.

func NewDumper

func NewDumper(w io.Writer, opts ...Option) (*Dumper, error)

NewDumper returns a new Dumper that writes to w with the given options.

func (*Dumper) Close

func (d *Dumper) Close() error

Close closes the Dumper by writing any remaining data. It does not write a stream terminating string "...".

func (*Dumper) Dump

func (d *Dumper) Dump(in any) error

Dump writes the YAML encoding of v to the stream.

If multiple values are dumped to the stream, the second and subsequent documents will be preceded with a "---" document separator.

See the documentation for Marshal for details about the conversion of Go values to YAML.

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

An Encoder writes YAML values to an output stream.

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that writes to w. It uses v3-compatible serialization options and the v4 error formatter. The Encoder should be closed after use to flush all data to w.

func (*Encoder) Close

func (e *Encoder) Close() error

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

func (e *Encoder) Encode(v any) error

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.

func (*Encoder) SetIndent

func (e *Encoder) SetIndent(spaces int)

SetIndent changes the used indentation used when encoding.

It panics if spaces is negative. Non-negative values outside 2-9 may be silently reset to 2 when encoding starts.

This method should be considered deprecated because it cannot return an error for invalid indentation. Use NewDumper with WithIndent instead.

type Encoding

type Encoding = libyaml.Encoding

Encoding represents the character encoding of a [Stream.Encoding].

type ErrorFormatPlugin

type ErrorFormatPlugin interface {
	// FormatLoadError returns the string representation of a LoadError.
	// The returned string is used as the error message.
	FormatLoadError(err *LoadError) string

	// FormatDumpError returns the string representation of a DumpError.
	// The returned string is used as the error message.
	FormatDumpError(err *DumpError) string
}

ErrorFormatPlugin customizes how YAML load and dump errors are rendered.

When registered, FormatLoadError and FormatDumpError are called to produce the error message string for each LoadError and DumpError, allowing the format to be customized.

Example usage:

import errorformatv3 "go.yaml.in/yaml/v4/plugin/errorformat/v3"
loader, err := yaml.NewLoader(reader, yaml.WithPlugin(errorformatv3.New()))

type IndentConfig

type IndentConfig = libyaml.IndentConfig

IndentConfig configures tab-indentation loading and dumping.

type IndentMode

type IndentMode = libyaml.IndentMode

IndentMode supplies loading and dumping defaults.

type IndentScope

type IndentScope = libyaml.IndentScope

IndentScope controls how long an auto-detected style remains active.

type IndentStyle

type IndentStyle = libyaml.IndentStyle

IndentStyle identifies the characters used for structural indentation.

type IsZeroer

type IsZeroer = libyaml.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 Kind

type Kind = libyaml.Kind

Kind represents the type of YAML node.

type LineBreak

type LineBreak = libyaml.LineBreak

LineBreak represents the line ending style for YAML output.

type LoadError

type LoadError = libyaml.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 Loader

type Loader struct {
	// contains filtered or unexported fields
}

Loader reads and loads YAML values from an input stream with configurable options.

func NewLoader

func NewLoader(r io.Reader, opts ...Option) (*Loader, error)

NewLoader returns a new Loader that reads from r with the given options.

The Loader introduces its own buffering and may read data from r beyond the YAML values requested.

func (*Loader) Load

func (l *Loader) Load(out any) error

Load reads the next YAML-encoded document from its input and stores it in the value pointed to by `out`.

Returns io.EOF when there are no more documents to read.

If the WithSingleDocument option was set and a document was already read, subsequent calls return io.EOF.

Maps and pointers (to a struct, string, int, etc) are accepted as values for `out` values.

If an internal pointer within a struct is not initialized, the yaml package will initialize it if necessary for loading the provided data.

The `out` parameter must not be nil.

The type of the decoded values should be compatible with the respective values in the `out` parameter.

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 loaded if they are exported (have an upper case first letter), and are loaded 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 loading process (see Load). Conflicting names result in a runtime error.

See the documentation of the package-level Load function for more details about YAML to Go conversion and tag options.

type LoaderLimitsPlugin

type LoaderLimitsPlugin 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
}

LoaderLimitsPlugin configures safety limits for YAML loading.

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/loaderlimits"
loader, err := yaml.NewLoader(reader,
    yaml.WithPlugin(loaderlimits.New(loaderlimits.AliasNone())))

type Mark

type Mark = libyaml.Mark

Mark represents a position in the YAML document.

type Marshaler

type Marshaler = libyaml.Marshaler

Marshaler interface may be implemented by types to customize their behavior when being marshaled into a YAML document.

type MergeKeyConfig

type MergeKeyConfig = libyaml.MergeKeyConfig

MergeKeyConfig controls merge recognition, repeated directives, and conflicts.

type MergeKeyInput

type MergeKeyInput = libyaml.MergeKeyInput

MergeKeyInput supplies read-only target and source mappings to an algorithm.

type MergeKeyPlugin

type MergeKeyPlugin = libyaml.MergeKeyPlugin

MergeKeyPlugin chooses the effective mapping before value construction.

type Node

type Node = libyaml.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

type Option = libyaml.Option

Option allows configuring YAML loading and dumping operations.

func Options

func Options(opts ...Option) Option

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

func OptsYAML(yamlStr string) (Option, error)

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 API to config)

The plugin field configures plugins by API. Each value is a configuration map or string, true for the default implementation, or false to leave the plugin disabled. A map may select an implementation with "name" and require its exact release with "version". Versions may include a leading "v". A map may contain "disable": true to leave the plugin disabled. The "name", "version", and "disable" host fields are not passed to the plugin factory. "disable": false keeps the plugin enabled. Null plugin values are invalid. Currently supported: "loader-limits" with keys "depth" and "alias" (int or null to disable). The "error-format" API accepts a "v3" or "v4" formatter config. An unversioned string first selects a registered implementation. Otherwise, it may name an empty configuration entry accepted by the default factory: "error-format: v3" is equivalent to "error-format: {v3: {}}".

Only fields specified in the YAML will override other options when combined. Unspecified fields won't affect other options. To clear an earlier single-document setting, apply WithSingleDocument(false) after the parsed configuration.

Example:

opts, err := yaml.OptsYAML(`
  indent: 3
  known-fields: true
  plugin:
    loader-limits:
      depth: 50
    error-format:
      v4:
        position: long
`)
if err != nil {
    return err
}
output, err := yaml.Dump(&data, opts)

func WithNamedPlugin

func WithNamedPlugin(api string) Option

WithNamedPlugin selects the implementation whose name matches the API.

func WithPlugin

func WithPlugin(plugins ...any) Option

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:

  • AliasDataPlugin: Controls anchor storage and alias resolution
  • LoaderLimitsPlugin: Controls depth and alias expansion limits
  • MergeKeyPlugin: Chooses effective mappings before construction
  • ParserPlugin: Supplies a complete YAML event stream
  • TabIndentPlugin: Enables tab-aware loading and tab-indented dumping
  • ErrorFormatPlugin: Customizes load and dump error message formatting

Example:

import "go.yaml.in/yaml/v4/plugin/loaderlimits"
loader, err := yaml.NewLoader(reader,
    yaml.WithPlugin(loaderlimits.New(loaderlimits.AliasNone())))

Plugins use public types and can be implemented by external packages.

func WithV2Defaults

func WithV2Defaults() Option

WithV2Defaults returns V2-compatible default options. It uses the current v4 error formatter. To select legacy-style error strings, apply WithPlugin(errorformatv3.New()) after this preset.

func WithV3Defaults

func WithV3Defaults() Option

WithV3Defaults returns default options for go-yaml v3 compatibility. Unmarshal uses these defaults. Marshal uses them with the line width overridden to -1 (unlimited). Dump with this preset uses a line width of 80 unless overridden, so its output may wrap differently from Marshal.

func WithV4Defaults

func WithV4Defaults() Option

WithV4Defaults returns the current V4 default options. These are the default settings when using Dump or Load without any options.

type ParserPlugin

type ParserPlugin = libyaml.ParserPlugin

ParserPlugin supplies a complete event stream in place of native parsing.

type PluginEvent

type PluginEvent = libyaml.PluginEvent

PluginEvent carries source-independent YAML syntax information.

type PluginFactory

type PluginFactory = pluginreg.Factory

PluginFactory constructs a plugin from its plugin-specific configuration.

type PluginRegistration

type PluginRegistration = pluginreg.Registration

PluginRegistration describes one named implementation of a plugin API. Version is empty for an unversioned implementation. Default selects the implementation used by boolean configuration.

type QuoteStyle

type QuoteStyle = libyaml.QuoteStyle

QuoteStyle represents the quote style to use when quoting is required.

type Stage

type Stage = libyaml.Stage

Stage identifies the processing stage where an error occurred during YAML loading or dumping.

type Stream

type Stream = libyaml.Stream

Stream holds stream-level metadata for StreamNode. This includes encoding, version directive, and tag directives.

type Style

type Style = libyaml.Style

Style represents the formatting style of a YAML node.

type TabIndentPlugin

type TabIndentPlugin = libyaml.TabIndentPlugin

TabIndentPlugin enables tab-aware structural indentation.

type TagDirective

type TagDirective = libyaml.StreamTagDirective

TagDirective represents a YAML %TAG directive for [Stream.TagDirectives].

type TypeError deprecated

type TypeError = libyaml.TypeError

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

VersionDirective represents a YAML %YAML version directive for [Stream.Version].

Directories

Path Synopsis
cmd
go-yaml command
example
basic_dumper command
basic_loader command
load_into_node command
node_dump_with_options command
Node Dump With Options demonstrates node styles and output formatting.
Node Dump With Options demonstrates node styles and output formatting.
version_options command
with_v4_option command
internal
libyaml
Package libyaml implements go-yaml's internal load and dump pipelines.
Package libyaml implements go-yaml's internal load and dump pipelines.
plugin
Package plugin implements the named plugin registry.
Package plugin implements the named plugin registry.
plugin/mergekey
Package mergekey implements the default Merge-Key algorithm.
Package mergekey implements the default Merge-Key algorithm.
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.
aliasdata
Package aliasdata supplies node-based YAML anchor and alias policies.
Package aliasdata supplies node-based YAML anchor and alias policies.
errorformat
Package errorformat contains versioned YAML load and dump error formatting plugins.
Package errorformat contains versioned YAML load and dump error formatting plugins.
errorformat/v3
Package errorformatv3 provides the go-yaml v3-compatible error formatter.
Package errorformatv3 provides the go-yaml v3-compatible error formatter.
errorformat/v4
Package errorformatv4 provides the go-yaml v4 error formatter.
Package errorformatv4 provides the go-yaml v4 error formatter.
loaderlimits
Package loaderlimits provides configurable loader limits for go-yaml.
Package loaderlimits provides configurable loader limits for go-yaml.
mergekey
Package mergekey supplies the standard shallow Merge-Key algorithm.
Package mergekey supplies the standard shallow Merge-Key algorithm.
tabindent
Package tabindent configures structural YAML indentation.
Package tabindent configures structural YAML indentation.
util
build-cli command
Build a CLI with CONFIG, PLUGIN, and PLUGIN-PACKAGE settings.
Build a CLI with CONFIG, PLUGIN, and PLUGIN-PACKAGE settings.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址