Documentation
¶
Overview ¶
Package yaml reads and writes YAML documents.
Marshal and Unmarshal cover the ordinary case, as in the standard library's encoding packages, and take no option.
FromJSON and ToJSON provides efficient conversions without the need for an intermediary (lossy) representation as a go value.
For advanced usage, explore a layer down:
- codec holds Encoder and Decoder, with options that steer how serialization works: MapSlice, RawMessage, comments, ... Use codec.NewDecoder to read a stream and codec.Unmarshal to pass an option.
- github.com/go-openapi/go-yaml/ast holds a document, whole or partial, as a tree of nodes.
- github.com/go-openapi/go-yaml/parser builds that tree from a source document.
- github.com/go-openapi/go-yaml/errors declares the failure every one of them reports, with the position it happened at.
- github.com/go-openapi/go-yaml/expressions navigates a document by path.
Internals ¶
- github.com/go-openapi/go-yaml/internal/scanner produces tokens for the parser.
Tags ¶
A tag is read by the URI it names rather than by the shorthand it was written with, so "!!int", "!<tag:yaml.org,2002:int>" and "!e!int" under "%TAG !e! tag:yaml.org,2002:" are one tag. The expansion is on the node, at github.com/go-openapi/go-yaml/ast.TagNode.URI.
The seven tags of the YAML 1.2 core schema (§10.2) are resolved: !!null, !!bool, !!int, !!float, !!str, !!seq and !!map.
Five more come from the 1.1 type repository at https://yaml.org/type and are resolved as well, under either version:
- !!binary decodes base64 into []byte, and a text base64 cannot read is an error.
- !!merge is the "<<" key, whose mapping's entries are folded into the one holding it.
- !!omap has to stand on a sequence and decodes as one, in the order it was written. There is no ordered-map type behind it; use codec.UseOrderedMap to get codec.MapSlice for every mapping.
- !!set has to stand on a mapping and decodes as a map with nil values.
- !!timestamp decodes to a time.Time, and a text no format reads is an error. The formats are the ones yaml.org/type/timestamp.html spells.
!!timestamp takes two rules, since YAML 1.2 has no timestamp of its own and other libraries differ. An explicit !!timestamp resolves whatever version the document declares, because a tag names a URI and is not resolution. An untagged "2001-12-14" is a string in both versions, and only a Go field of type time.Time asks for the conversion -- go.yaml.in/yaml/v3 reads it as a time.Time and gopkg.in/yaml.v2 as a string. github.com/go-openapi/go-yaml/parser.WithYAMLVersion and a "%YAML" directive select what an untagged plain scalar resolves to, and neither changes what a tag means.
Three tags of the 1.1 repository are not resolved: !!pairs, !!value and !!yaml. They are parsed and carried on the node like any other tag, and the value under them stands as it was written. So does every tag outside these fifteen -- a local "!thing", a handle a "%TAG" line declared, another namespace -- with one rule: a tag nothing resolves leaves its scalar as text, digits and all, so "!thing 12" is the string "12". §6.9.1 hands a local tag to the application, so none of these is an error.
A tag naming a type its scalar is not ¶
"!!int abc" is an assertion that does not hold, and by default it is an error naming both: cannot read "abc" as !!int. The same goes for !!bool, !!float, !!null, !!binary and !!timestamp.
YAML leaves this open. §3.1.2 builds a representation from the serialization, and a node whose tag will not apply has none to build; what a processor then owes the caller is not stated, so refusing, zeroing and echoing the text are all conformant. This library refused three of the six and answered the other three with a zero until 2026-09-07, which meant a caller could not tell "!!int abc" from a written 0.
github.com/go-openapi/go-yaml/parser.WithLaxTags reads the text instead, so "!!int abc" is the string "abc". The tag stays on the node either way and a render writes it back, so a document read laxly still round-trips.
Two things stay strict. A tag naming a kind its node is not -- "!!seq 5" -- is reported whatever the policy, since no text stands in for a sequence. And a tag the YAML 1.2 grammar has no production for, such as "!<>" or "!!<x>", is refused as the document is scanned.
The verdict is the node's own, at github.com/go-openapi/go-yaml/ast.TagNode.Resolve, so every consumer of one tree gives one answer: Unmarshal, codec.ToJSON and a caller holding a single node all read it there.
Anchors and aliases ¶
An alias builds its own value. "first: *b" and "second: *b" give two maps, so a caller writing through one leaves the other alone, and a document naming far more than it holds -- 259 bytes of nested aliases name 100,000 values -- is refused with github.com/go-openapi/go-yaml/errors.ErrExcessiveAliasing rather than built.
codec.ShareAliases hands every alias of one anchor the same value instead. Ask for it when the anchors have to survive a round trip through a Go value: codec.MarshalAnchor, codec.WithSmartAnchor and the ",anchor" and ",alias" struct tags find an anchor by the address its value stands at, so an encoder can write "*name" only where the decode left one value under two names. Reading a document into an github.com/go-openapi/go-yaml/ast tree and rendering it keeps the anchors either way; this is about the Go value.
Sharing was the default until 2026-09-07, and whether it applied turned on whether the destination happened to declare a field for the anchor itself.
Example (Colorize) ¶
Example_colorize renders a document through a hook, which sees every stretch of text the renderer writes and the node it belongs to. The renderer writes the source back as it was read, so a hook decorates the text and changes nothing else.
Replace markup with colorize.Default() and the output with os.Stdout to print the document in color to a terminal.
// SPDX-FileCopyrightText: Copyright 2025 go-swagger maintainers
// SPDX-License-Identifier: Apache-2.0
package main
import (
"fmt"
"io"
"os"
"github.com/go-openapi/go-yaml/ast"
"github.com/go-openapi/go-yaml/parser"
"github.com/go-openapi/go-yaml/transform/colorize"
)
// markup is a theme that writes tags instead of colors, so the result can be read in a test. colorize.Default is the
// theme for a terminal: it writes the same document with ANSI escapes.
var markup = colorize.Theme{
Key: colorize.Style{Prefix: "<key>", Suffix: "</key>"},
String: colorize.Style{Prefix: "<str>", Suffix: "</str>"},
Integer: colorize.Style{Prefix: "<int>", Suffix: "</int>"},
Bool: colorize.Style{Prefix: "<bool>", Suffix: "</bool>"},
Anchor: colorize.Style{Prefix: "<anchor>", Suffix: "</anchor>"},
Alias: colorize.Style{Prefix: "<alias>", Suffix: "</alias>"},
Comment: colorize.Style{Prefix: "<comment>", Suffix: "</comment>"},
Indicator: colorize.Style{Prefix: "<ind>", Suffix: "</ind>"},
}
// stretches is a rendering hook that writes one line per stretch of text the renderer hands it, with the node and the
// token the stretch came from. Use it to see what a hook such as colorize.New is given to work with.
func stretches(w io.Writer, s ast.Written) error {
kind, tk := "-", "-"
if s.Node != nil {
kind = s.Node.Type().String()
}
if s.Token != nil {
tk = s.Token.Type.String()
}
_, err := fmt.Fprintf(w, "%-12s %-12s key=%-5v %q\n", kind, tk, s.Key, s.Text)
return err
}
// Example_colorize renders a document through a hook, which sees every stretch of text the renderer writes and the
// node it belongs to. The renderer writes the source back as it was read, so a hook decorates the text and changes
// nothing else.
//
// Replace markup with colorize.Default() and the output with os.Stdout to print the document in color to a terminal.
func main() {
src := []byte("# defaults\nbase: &b {port: 8080}\nprod: *b # same\ndebug: true\n")
file, err := parser.ParseBytes(src, parser.WithComments())
if err != nil {
fmt.Println(err)
return
}
for _, hook := range []ast.TransformFunc{colorize.New(markup), stretches} {
r := ast.NewRenderer(ast.WithSource(src), ast.WithTransform(hook))
if err := r.VerbatimFile(os.Stdout, file); err != nil {
fmt.Println(err)
return
}
}
}
Output: <comment># defaults</comment> <key>base</key><ind>:</ind> <anchor>&</anchor><anchor>b</anchor> <ind>{</ind><key>port</key><ind>:</ind> <int>8080</int><ind>}</ind> <key>prod</key><ind>:</ind> <alias>*</alias><alias>b</alias> <comment># same</comment> <key>debug</key><ind>:</ind> <bool>true</bool> Comment Comment key=false "# defaults" - - key=true "\n" String String key=true "base" MappingValue MappingValue key=false ":" - - key=false " " Anchor Anchor key=false "&" Anchor String key=false "b" - - key=false " " Mapping MappingStart key=false "{" String String key=true "port" MappingValue MappingValue key=false ":" - - key=false " " Integer Integer key=false "8080" Mapping MappingEnd key=false "}" - - key=true "\n" String String key=true "prod" MappingValue MappingValue key=false ":" - - key=false " " Alias Alias key=false "*" Alias String key=false "b" - - key=false " " Comment Comment key=false "# same" - - key=true "\n" String String key=true "debug" MappingValue MappingValue key=false ":" - - key=false " " Bool Bool key=false "true" - - key=false "\n"
Example (ErrorSource) ¶
Example_errorSource prints an error with the lines of the document around it: the line in error is marked with ">" and a caret points at the column.
Pass colored as true to [yamlerrors.FormatError] to print the message and the margin with ANSI colors for a terminal, and inclSource as false to print the position and the message alone.
package main
import (
"fmt"
"github.com/go-openapi/go-yaml"
yamlerrors "github.com/go-openapi/go-yaml/errors"
)
func main() {
src := []byte("server:\n host: example.com\n port: 443\n host: example.org\n debug: true\n")
var v map[string]any
if err := yaml.Unmarshal(src, &v); err != nil {
fmt.Println(yamlerrors.FormatError(err, false, true))
}
}
Output: [4:3] mapping key "host" already defined at [2:3] 1 | server: 2 | host: example.com 3 | port: 443 > 4 | host: example.org ^ 5 | debug: true
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FromJSON ¶
FromJSON converts a JSON document to the YAML that holds the same values, and rejects input that is not JSON.
See codec.FromJSON for what is written, and for the options that lay it out.
Example ¶
package main
import (
"fmt"
"github.com/go-openapi/go-yaml"
)
func main() {
out, err := yaml.FromJSON([]byte(`{"name":"go-yaml","versions":[1.1,1.2],"stable":true}`))
if err != nil {
fmt.Println(err)
return
}
fmt.Print(string(out))
}
Output: name: go-yaml versions: - 1.1 - 1.2 stable: true
func Marshal ¶
Marshal serializes a go value v into a YAML document.
See codec.Marshal for how a Go value is mapped onto YAML and what the struct tags mean.
Example ¶
package main
import (
"fmt"
"github.com/go-openapi/go-yaml"
)
type server struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
Tags []string `yaml:"tags,omitempty"`
Debug bool `yaml:"debug"`
}
func main() {
out, err := yaml.Marshal(server{Host: "localhost", Port: 8080, Tags: []string{"api", "v2"}})
if err != nil {
fmt.Println(err)
return
}
fmt.Print(string(out))
}
Output: host: localhost port: 8080 tags: - api - v2 debug: false
func ToJSON ¶
ToJSON converts a YAML document to the JSON that holds the same values.
See codec.ToJSON for advanced usage with options.
Example ¶
package main
import (
"fmt"
"github.com/go-openapi/go-yaml"
)
func main() {
out, err := yaml.ToJSON([]byte("name: go-yaml\nversions: [1.1, 1.2]\nstable: true\n"))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(out))
}
Output: {"name":"go-yaml","versions":[1.1,1.2],"stable":true}
func Unmarshal ¶
Unmarshal decodes a YAML document into the go value pointed to by v.
See codec.Unmarshal for how a YAML document is mapped onto a Go value.
Example ¶
package main
import (
"fmt"
"github.com/go-openapi/go-yaml"
)
type server struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
Tags []string `yaml:"tags,omitempty"`
Debug bool `yaml:"debug"`
}
func main() {
const doc = `
host: example.com
port: 443
debug: true
`
var s server
if err := yaml.Unmarshal([]byte(doc), &s); err != nil {
fmt.Println(err)
return
}
fmt.Printf("%+v\n", s)
}
Output: {Host:example.com Port:443 Tags:[] Debug:true}
Example (SyntaxError) ¶
A document that is not YAML returns an error matching [yamlerrors.ErrSyntax], which carries the position it was found at.
package main
import (
"errors"
"fmt"
"github.com/go-openapi/go-yaml"
yamlerrors "github.com/go-openapi/go-yaml/errors"
)
type server struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
Tags []string `yaml:"tags,omitempty"`
Debug bool `yaml:"debug"`
}
func main() {
var s server
err := yaml.Unmarshal([]byte("host: [a, b\n"), &s)
var yerr *yamlerrors.Error
if errors.Is(err, yamlerrors.ErrSyntax) && errors.As(err, &yerr) {
pos := yerr.GetToken().Position
fmt.Printf("line %d, column %d: %s\n", pos.Line, pos.Column, yerr.GetMessage())
}
}
Output: line 1, column 7: a flow sequence is not closed by ']'
Types ¶
This section is empty.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package codec converts between YAML documents and Go values, with options.
|
Package codec converts between YAML documents and Go values, with options. |
|
internal/astutils
Package astutils holds the codec's helpers that read or edit an ast tree.
|
Package astutils holds the codec's helpers that read or edit an ast tree. |
|
internal/codecutils
Package codecutils holds the codec's helpers that read and convert Go values.
|
Package codecutils holds the codec's helpers that read and convert Go values. |
|
internal/structfields
Package structfields reads the fields a Go struct type shows to the codec: the name each is written under, its `yaml` flags, and the fields an embedded or `,inline` struct promotes.
|
Package structfields reads the fields a Go struct type shows to the codec: the name each is written under, its `yaml` flags, and the fields an embedded or `,inline` struct promotes. |
|
Package errors reports what went wrong reading or writing a YAML document, with the position it happened at and the lines of source around it.
|
Package errors reports what went wrong reading or writing a YAML document, with the position it happened at and the lines of source around it. |
|
Package expressions addresses nodes inside a YAML document with YAML Path expressions, such as "$.store.book[0].author".
|
Package expressions addresses nodes inside a YAML document with YAML Path expressions, such as "$.store.book[0].author". |
|
internal
|
|
|
conformance
Package conformance measures github.com/go-openapi/go-yaml/ast.Renderer against the YAML Test Suite.
|
Package conformance measures github.com/go-openapi/go-yaml/ast.Renderer against the YAML Test Suite. |
|
corpus
Package corpus generates the synthetic documents the benchmarks run on.
|
Package corpus generates the synthetic documents the benchmarks run on. |
|
excerpt
Package excerpt draws the lines of a document around a token, which is what an error prints under its message.
|
Package excerpt draws the lines of a document around a token, which is what an error prints under its message. |
|
fuzzseeds
Package fuzzseeds supplies the shared seed corpus for the fuzz targets.
|
Package fuzzseeds supplies the shared seed corpus for the fuzz targets. |
|
ledgers
Package ledgers provides the two ratchets the defect ledgers are checked with.
|
Package ledgers provides the two ratchets the defect ledgers are checked with. |
|
nocopy
Package nocopy makes a string that shares a byte slice's memory.
|
Package nocopy makes a string that shares a byte slice's memory. |
|
probe
Package probe counts what the library did, for tests that ask a question no output answers.
|
Package probe counts what the library did, for tests that ask a question no output answers. |
|
scanner
Package scanner turns the bytes of a YAML stream into tokens.
|
Package scanner turns the bytes of a YAML stream into tokens. |
|
scanner/internal/testscanner
Package testscanner provides testing utilities to the scanner package.
|
Package testscanner provides testing utilities to the scanner package. |
|
scanner/swar
Package swar scans eight bytes of a document at a time, in one register.
|
Package swar scans eight bytes of a document at a time, in one register. |
|
testcorpus
Package testcorpus reads the workload documents the measurements across this repository run against.
|
Package testcorpus reads the workload documents the measurements across this repository run against. |
|
tokenarena
Package tokenarena holds the tokens of a parse in chunks it can reuse.
|
Package tokenarena holds the tokens of a parse in chunks it can reuse. |
|
yamlpath
Package yamlpath reads, merges into and replaces the nodes a YAML Path addresses.
|
Package yamlpath reads, merges into and replaces the nodes a YAML Path addresses. |
|
analysis
module
|
|
|
Package parser reads a YAML stream into an ast.File.
|
Package parser reads a YAML stream into an ast.File. |
|
internal/key
Package key finds a mapping key that a document has already used.
|
Package key finds a mapping key that a document has already used. |
|
Package token defines the lexical tokens of a YAML document, and the rules that type and convert a plain scalar.
|
Package token defines the lexical tokens of a YAML document, and the rules that type and convert a plain scalar. |
|
Package transform rewrites a YAML document a piece at a time: Walk reads the document and calls a Transformer, which writes each piece unchanged or rewritten.
|
Package transform rewrites a YAML document a piece at a time: Walk reads the document and calls a Transformer, which writes each piece unchanged or rewritten. |
|
colorize
Package colorize writes a YAML document back out with ANSI colors.
|
Package colorize writes a YAML document back out with ANSI colors. |