yaml

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 1 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-yaml

Tests Coverage CI vuln scan CodeQL

Release CodeFactor Grade License

Doc GoDoc Discord Channel go version Top language Commits since latest release

A Go library to work with YAML documents.

Why choose go-openapi/go-yaml

This library will prove useful when:

  • You want a strict YAML 1.2 parser, with control over the YAML idiom
  • You need a low-level API to parse or transform YAML documents
  • You are constrained by memory: this library is particularly efficient on memory usage
  • You need a fast and lossless way to convert JSON to YAML and back
  • You want to use YAMLPath expressions
  • You want to overcome classic limitations of native go types for numerical values
  • You need a programmatic API to manipulate YAML documents, including custom tags and comments, with full control over the document layout and on-the-fly transformations

If you only need to hydrate Go values from YAML, and don't care about any of the above, use go.yaml.in/yaml/v3 instead: it's stable, it's maintained, it works.

yaml/v3 is already reasonably conformant to YAML 1.2, and we have tried hard to improve on that part. You may watch how conformance stands on various parsers there.

Status

Early days. The API remains subject to changes.

[!WARNING]

This library is still in its early days.

It is a hard fork of goccy/go-yaml. A lot of work has been issued on top of our fork point (edee2f91616c6d73112a13e7c0dbde72ce938877), and the exported API is still in flux.

The posture we have adopted for various YAML puzzles may be debatable and might need to be revisited.

Motivation & goals

  1. At go-openapi we consume and produce a lot of YAML. A typical API spec can be a fairly large document, so we need an efficient parser for those, both in terms of CPU cycles and memory.
  2. We also face a lot of challenges when dealing with YAML that your typical go program won't care about, like keeping the order of keys, the comments, or supporting out-of-range numericals.

What we need is:

  • a relatively fast, memory-efficient YAML parser, written in pure go
  • a low-level API to parse, transform and render YAML streams
  • ways to process YAML without the need for an intermediate Go value representation

In addition, we want this lib to bring tools for advanced work with YAML documents:

  • a strict YAML 1.2 parser, with optional support for YAML 1.1
  • full support of YAML constructs, including comments, aliases, tags, custom tags, non-scalar keys, directives etc
  • verbatim rendering of a parsed document, without loss (e.g. comments, layout style, indentation, ordering)

Features

  • full YAML 1.2 support, strict by default, with optionally relaxed constraints
  • codec for go: Unmarshal,Marshal,Decoder,Encoder
    • also provides: fast, lossless transforms ToJSON (from YAML), FromJSON (to YAML) and a JSON tokenizer
  • low-level API: parser, renderer able to render a document verbatim, extract comments, etc
  • document transforms (examples: colorizer, custom tag parser)
  • YAML path expressions
  • programmatic document API via ast representation of a YAML document

See also our documentation for a detailed presentation of these features, and the differences with other libraries etc.

See the runnable examples in our go doc as well as the commented examples in the documentation.

Performances

Our main design goal for this lib was to reduce peak memory usage as much as we could, as well as garbage.

Example: decoding YAML into a Go value.

Each library unmarshals each workload into an any, built with PGO from one shared profile. Times are the median of 6 runs; peak memory is the highest live heap during the decode.

workload source time: go-openapi v3 goccy peak: go-openapi v3 goccy
azure_swagger 0.52 MiB 26 ms 36 ms 54 ms 2.39 MiB 6.37 MiB 17.13 MiB
canada_geometry 0.38 MiB 20 ms 45 ms 39 ms 0.56 MiB 4.54 MiB 12.75 MiB
citm_catalog 0.56 MiB 61 ms 60 ms 107 ms 4.88 MiB 14.75 MiB 35.83 MiB
citm_catalog_flow 0.69 MiB 62 ms 64 ms 107 ms 4.81 MiB 14.94 MiB 41.83 MiB
commented_swagger 0.57 MiB 27 ms 35 ms 53 ms 2.38 MiB 6.76 MiB 17.60 MiB
golang_source 3.61 MiB 163 ms 186 ms 300 ms 8.32 MiB 38.07 MiB 116.94 MiB
twitter_status 0.48 MiB 29 ms 35 ms 56 ms 1.76 MiB 5.97 MiB 14.89 MiB

v3 is go.yaml.in/yaml/v3. goccy is upstream github.com/goccy/go-yaml.

Our implementation of YAML decode brings only a modest time improvement compared to yaml/v3 (e.g. 0 to 25% faster), but with a massive reduction in memory activity (allocated garbage and peak memory).

Our peak stays near the size of the decoded Go value: the decoding process holds little besides its result.

citm_catalog is our least favourable workload for a decode into any: our time is on a par with v3's, 61 ms against 60 ms. This workload is where v3's parser shines: it is simpler than ours and optimized specifically for decoding Go values, whereas our parser pays the cost of full support for YAML features, even those not consumed by the decode use-case.

Decoding citm_catalog into its Go types, v3 takes 64 ms against our 81 ms, and goccy 134 ms. Our peak is 0.68 MiB, against 11.31 MiB for v3 and 34.95 MiB for goccy: the decode builds no tree, so it holds little besides the 0.57 MiB value it returns.

Encoding and converting go further. Marshal writes the document as it walks the value, takes 39% to 52% of v3's time and peaks between 1/10th to 1/30th of v3's live heap (6.1 MiB against 117 MiB on golang_source).

FromJSON reads JSON with the lexer of go-openapi/core/json and takes 22% to 34% of the time of v3's route, json.Unmarshal then Marshal.

See internal/benchmarks for decoding into a struct, ToJSON, FromJSON and encoding, for the command that reproduces these figures, and for how garbage collection decides the comparison: with the collector off, v3's simpler parse decodes citm_catalog, its flow-style form and twitter_status faster than ours.

Measured on 2026-11-28 with go.yaml.in/yaml/v3 v3.0.6 and github.com/goccy/go-yaml v1.19.2, on an AMD Ryzen 7 5800X.

Known limitations

By design limitations - they'll stay here:

  • only support UTF-8 encoding

no UTF-16 support is offered: you need to encode any UTF-16 input prior to parsing.

Transitory limitations - we are currently working on those.

  • no streaming support: a decoder reads the whole of its io.Reader before it parses
  • codecand transform API to support preset rendering styles, such as KYAML or others
  • transform API to support YAML version conversion
  • known issues
    • Decode into struct: null values should not default to a zero value to coerce a non-nullable type.
    • Performance: high-level API to recycle a parser from a pool

Credits

This library was forked from the work started by Masaaki Goshima (@goccy), which is maintained upstream at github.com/goccy/go-yaml.

We are grateful to Masaaki for this great piece of work. This fork tries to remain faithful to its spirit: an independent YAML 1.2 library that brings to go developers advanced insight into YAML subtleties.

Our work was also inspired by some of the ideas and designs proposed by:

Reference

License

Apache-2.0 — see LICENSE.

This is a hard fork of goccy/go-yaml, whose MIT licence permits it. That licence, and the terms of every other component this library is built on, are recorded in the NOTICE.

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:

Internals

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

func FromJSON(bytes []byte) ([]byte, error)

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

func Marshal(v any) ([]byte, error)

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

func ToJSON(bytes []byte) ([]byte, error)

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

func Unmarshal(data []byte, v any) error

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.

Jump to

Keyboard shortcuts

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