---
title: "Extract a YAML section into another file in Go"
url: https://recursiveai.org/oneyaml/go/cookbook/export-yaml-subtree/
description: "Read a YAML section by path in Go and write it as a standalone YAML file without defining a struct for its fields."
version: "1.0.0"
---

# Extract a YAML section into another file 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/export-yaml-subtree/export-yaml-subtree.zip)

Use `Get` to read `/spec`, then `Marshal` to export its value. This copies the data, not the comments or layout.

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

Requires Go 1.24 or later. Run the install command in a Go module.

```go
package main

import (
	"fmt"
	"log"
	"os"

	"oneyaml.dev/go"
)

func main() {
	input := "name: api\n" +
		"spec: {replicas: 2}\n"
	doc, err := oneyaml.Parse([]byte(input))
	if err != nil {
		log.Fatal(err)
	}
	var section oneyaml.Node
	if err := doc.Get("/spec", &section); err != nil {
		log.Fatal(err)
	}
	out, err := oneyaml.Marshal(section)
	if err != nil {
		log.Fatal(err)
	}
	err = os.WriteFile("spec.yaml", out, 0644)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(string(out))
}
```

Running this snippet writes `spec.yaml` and prints:

```text
replicas: 2
```

## The full program

Unzip [the example](https://recursiveai.org/oneyaml/go/cookbook/export-yaml-subtree/export-yaml-subtree.zip), then `go run .`.

The download reads this `config.yaml` and writes `spec.yaml` without changing `config.yaml`.

```yaml
name: api
spec: {replicas: 2, tier: web} # deploy settings
```

```go
package main

import (
	"fmt"
	"log"
	"os"

	"oneyaml.dev/go"
)

func main() {
	input, err := os.ReadFile("config.yaml")
	if err != nil {
		log.Fatal(err)
	}
	doc, err := oneyaml.Parse(input)
	if err != nil {
		log.Fatal(err)
	}
	var section oneyaml.Node
	if err := doc.Get("/spec", &section); err != nil {
		log.Fatal(err)
	}
	out, err := oneyaml.Marshal(section)
	if err != nil {
		log.Fatal(err)
	}
	err = os.WriteFile("spec.yaml", out, 0644)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(string(out))
}
```

`go run .` prints the contents of `spec.yaml`:

```text
replicas: 2
tier: web
```

If the path doesn’t exist, `Get` returns an error and this program exits before writing the output file.

## Variations

**Keep the `spec:` key around the exported value.** Replace the `Marshal` line in the snippet at the top:

```go
out, err := oneyaml.Marshal(map[string]oneyaml.Node{
	"spec": section,
})
```

```text
spec:
  replicas: 2
```

## Related recipes

- [Read YAML in Go without a struct](https://recursiveai.org/oneyaml/go/cookbook/read-yaml-without-a-struct/)
- [Find a YAML value in the source file](https://recursiveai.org/oneyaml/go/cookbook/locate-yaml-value-in-source/)

## The short answer

Call `Document.Get` with the section’s path and a `*oneyaml.Node` destination, then pass the populated node to `Marshal`. The output file contains the value at that path. `/spec` points to the mapping to the right of `spec:`, so the exported file starts with `replicas:`, not `spec:`. Keep the outer key only if the tool that consumes the new file expects it.

## How do you parse a nested YAML section in Go?

Parse the complete input first. The outer document gives the parser the context it needs to find the node, so you don’t have to locate a line with a matching key name and guess where the section ends. For example, `/deployment/spec` selects `spec` inside `deployment`, while `/services/0` selects the first item in a list named `services`. The [editing guide](https://recursiveai.org/oneyaml/go/docs/editing/) describes the path syntax (JSON Pointer): `/` separates steps, `~1` represents a slash inside a key, and `~0` represents a tilde. When building a path from a key you didn’t choose, use the library’s `Pointer` helper for escaping.

The `Node` is a view of the document, not a Go struct with fields you have to define first. The guide [shows reading it with `Get`](https://github.com/recursive-ai-oss/oneyaml-go/blob/7a4c8e39f041b945ee5f121c055f03bc2d7d01d9/docs/editing.md#L747-L779), not unmarshaling the input directly into a node. Export before editing the document, or fetch the node again after editing; a node you read before an edit is stale.

## Does marshaling a YAML section preserve its comments and formatting?

Not in this recipe. `Marshal` writes the node “as the value it holds.” In the downloaded example, the input has braces around the two fields and an inline comment after them. The new file has one key per line, with neither the braces nor the note. You can compare the shipped `config.yaml` with `spec.yaml` after running the program.

If you want the whole source document with a small change and its original formatting, edit the document and use `doc.Bytes()`. If you want just the selected value in a separate file, marshal the node. Writing that file doesn’t insert an include or other reference into the original.
