---
title: "Read YAML tags and directives in Go"
url: https://recursiveai.org/oneyaml/go/cookbook/read-yaml-tags-and-directives/
description: "Read the declared YAML version and tag prefixes in Go, and tell written tags apart from inferred types."
version: "1.0.0"
---

# Read YAML tags and directives in Go

**oneyaml-go** is a free, open-source YAML library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.

[pkg.go.dev](https://pkg.go.dev/oneyaml.dev/go) · [GitHub](https://github.com/recursive-ai-oss/oneyaml-go) · [Docs](https://recursiveai.org/oneyaml/go/docs/) · [Download example (.zip)](https://recursiveai.org/oneyaml/go/cookbook/read-yaml-tags-and-directives/read-yaml-tags-and-directives.zip)

Read the header with `Version()` and `TagDirectives()`. Use `ExplicitTag()` to tell written type tags from inferred ones. `%YAML` declares the spec version; `%TAG` maps a short handle like `!e!` to a full tag prefix.

```shell
go get oneyaml.dev/go@v1.0.0
```

Requires Go 1.24 or later. Run `go get` in a Go module.

```go
package main

import (
    "fmt"
    yaml "oneyaml.dev/go"
)

func main() {
    const input = `%YAML 1.2
%TAG !e! tag:example.com,2000:
---
point: !e!point [1, 2]
count: 2
`
    doc, err := yaml.Parse([]byte(input))
    if err != nil { panic(err) }
    fmt.Println(doc.Version())
    fmt.Println(doc.TagDirectives())
    for _, key := range []string{
        "point", "count",
    } {
        n, ok := doc.Root().Lookup(key)
        if !ok { panic("missing " + key) }
        tag, written := n.ExplicitTag()
        if !written { tag = n.Tag() }
        fmt.Println(key, tag, written)
        if written {
            fmt.Println(n.TagAsWritten())
        }
    }
}
```

Unzip [the example](https://recursiveai.org/oneyaml/go/cookbook/read-yaml-tags-and-directives/read-yaml-tags-and-directives.zip), then `go run .`.

```text
1 2 true
[{!e! tag:example.com,2000:}]
point tag:example.com,2000:point true
!e!point
count tag:yaml.org,2002:int false
```

## The full program

The download adds `label: !!str 1`, where `!!str` marks the value as a string even though it looks like a number.

```go
package main

import (
	"fmt"
	"log"

	yaml "oneyaml.dev/go"
)

func main() {
	const input = `%YAML 1.2
%TAG !e! tag:example.com,2000:
---
point: !e!point [1, 2]
label: !!str 1
count: 2
`
	doc, err := yaml.Parse([]byte(input))
	if err != nil {
		log.Fatal(err)
	}
	if major, minor, ok := doc.Version(); ok {
		fmt.Printf("%%YAML %d.%d\n", major, minor)
	}
	for _, directive := range doc.TagDirectives() {
		fmt.Printf("%%TAG %s %s\n", directive.Handle, directive.Prefix)
	}
	for _, key := range []string{"point", "label", "count"} {
		node, ok := doc.Root().Lookup(key)
		if !ok {
			log.Fatalf("missing key %q", key)
		}
		if tag, explicit := node.ExplicitTag(); explicit {
			fmt.Printf("%s: %s -> %s\n", key, node.TagAsWritten(), tag)
		} else {
			fmt.Printf("%s: %s (implicit)\n", key, node.Tag())
		}
	}
}
```

`go run .` prints:

```text
%YAML 1.2
%TAG !e! tag:example.com,2000:
point: !e!point -> tag:example.com,2000:point
label: !!str -> tag:yaml.org,2002:str
count: tag:yaml.org,2002:int (implicit)
```

An undeclared handle such as `!e!` without its `%TAG` directive causes a parse error; it isn’t an implicit tag.

## Variations

**Read the version of each document.** Append `...`, `---`, and `extra: 3` on separate lines to the full program’s input. After parsing that stream into `doc`, replace its printing code with this:

```go
fmt.Println(doc.Doc(0).Version())
fmt.Println(doc.Doc(1).Version())
```

The first line is `1 2 true`. The second is `0 0 false`: no version was declared for the second document.

## Related recipes

- [Read a multi-document YAML file in Go](https://recursiveai.org/oneyaml/go/cookbook/kubernetes-multi-document/)
- [Read YAML anchors, aliases and merge keys in Go](https://recursiveai.org/oneyaml/go/cookbook/anchors-aliases-merge-keys/)

## The short answer

Parse into a `Document` with oneyaml-go. `Version()` reports the declared major and minor version and whether the declaration exists. `TagDirectives()` gives you the handles and their prefixes. On a node, use `TagAsWritten()` for the original spelling and `ExplicitTag()` for its expanded form. If `ExplicitTag()` reports `false`, `Tag()` tells you the inferred tag without implying it was typed into the file.

## How do I use tags in YAML?

A [YAML tag](https://yaml.org/spec/1.2.2/#24-tags) identifies a type for a value. Put the tag before the value it describes. `!!str 1` uses a standard tag to say that `1` is a string. `!e!point [1, 2]` uses a custom tag to label the sequence as a point. The tag is metadata for the sequence; it isn’t an item in the sequence.

When an application inspects tags, it usually needs the expanded name. For example, two documents could choose different handles for the same prefix. Match against `tag:example.com,2000:point` rather than `!e!point` if those documents should mean the same thing to your tool. Keep the written spelling if you’re displaying what the author typed. When a check requires an explicit annotation, use the boolean from `ExplicitTag()`: a plain `2` gets the integer tag even though no tag appears before it.

## What do the `%YAML` and `%TAG` directives do?

The [YAML specification](https://yaml.org/spec/1.2.2/#68-directives) defines directives as instructions in the header, before the `---` document start. `%YAML 1.2` declares a version. `%TAG !e! tag:example.com,2000:` assigns the prefix `tag:example.com,2000:` to the short handle `!e!`, so `!e!point` expands to `tag:example.com,2000:point`.

In a stream, read declarations on the document you’re inspecting: `doc.Doc(0)` selects the first one, `doc.Doc(1)` the next. An absent `%YAML` directive is not a declaration of `0.0`. The [pinned API](https://github.com/recursive-ai-oss/oneyaml-go/blob/7a4c8e39f041b945ee5f121c055f03bc2d7d01d9/document_info.go#L25-L64) also distinguishes explicit `%TAG` declarations from the built-in tag handles.
