| 1 | # YAML Dumping and Loading API |
| 2 | |
| 3 | This guide covers go-yaml's dumping and loading APIs, |
| 4 | from simple one-liners to advanced streaming with full configuration control. |
| 5 | |
| 6 | ## Recommended API for v4+ |
| 7 | |
| 8 | **For new code in v4+, prefer `Dump`/`Load` over `Marshal`/`Unmarshal` and |
| 9 | `Encode`/`Decode`.** |
| 10 | |
| 11 | The classic API (`Marshal`, `Unmarshal`, `Encoder`, `Decoder`) remains |
| 12 | supported for compatibility, but `Dump`/`Load` and `Dumper`/`Loader` offer |
| 13 | more flexibility with options support. |
| 14 | |
| 15 | ### Why Dump and Load? |
| 16 | |
| 17 | The `Dump` and `Load` functions provide the same simplicity as |
| 18 | `Marshal`/`Unmarshal` while offering full control over YAML formatting and |
| 19 | parsing behavior through options: |
| 20 | |
| 21 | ```go |
| 22 | // Old way (v3 semantics, no options): |
| 23 | data, _ := yaml.Marshal(&config) |
| 24 | |
| 25 | // New way (v4 semantics by default + full options): |
| 26 | data, _ := yaml.Dump(&config) // v4 defaults: 2-space indent, compact |
| 27 | data, _ := yaml.Dump(&config, yaml.WithIndent(4)) // v4 with custom indent |
| 28 | ``` |
| 29 | |
| 30 | The names `Dump` and `Load` are from the YAML specification and also the most |
| 31 | common names used for these actions in actual YAML implementations. |
| 32 | |
| 33 | **Note**: Marshal, Unmarshal, Encode and Decode are not part of the standard |
| 34 | YAML vocabulary, but the are still fitting because go-yaml v2 and v3 did not |
| 35 | provide a full Dump and Load stack. |
| 36 | Those involve the Represent (for Dump) and Construct (for Load) YAML stack |
| 37 | stages and v4 will offer those (optionally) for Dump and Load. |
| 38 | |
| 39 | ### Classic API |
| 40 | |
| 41 | `Marshal`/`Unmarshal` and `Encode`/`Decode` provide a simple, options-free |
| 42 | interface: |
| 43 | |
| 44 | - They work **without options** and use **v3 semantics** (4-space |
| 45 | indent, non-compact sequences) |
| 46 | - They're perfect for simple use cases and upgrading existing v3 code |
| 47 | - For new code, use `Dump`/`Load` instead—they can replicate the same behavior |
| 48 | with added flexibility |
| 49 | |
| 50 | ### Flexibility |
| 51 | |
| 52 | With `Dump` and `Load`, you can choose your starting point: |
| 53 | |
| 54 | - **v4 semantics**: `yaml.Dump(&data)` (default: 2-space indent, compact |
| 55 | sequences) |
| 56 | - **v3 semantics**: `yaml.Dump(&data, yaml.WithV3Defaults())` (same |
| 57 | indentation and sequence style as Marshal: 4-space indent, non-compact) |
| 58 | - **v2 semantics**: `yaml.Dump(&data, yaml.WithV2Defaults())` (2-space indent, non-compact) |
| 59 | - **Custom options**: `yaml.Dump(&data, yaml.WithIndent(4), |
| 60 | yaml.WithExplicitStart())` |
| 61 | |
| 62 | This means `Dump` and `Load` default to modern v4 formatting, but can easily |
| 63 | replicate what `Marshal`/`Unmarshal` do, while also giving you complete control |
| 64 | when you need it. |
| 65 | |
| 66 | ## API Overview |
| 67 | |
| 68 | go-yaml provides five main API functions for dumping and loading YAML: |
| 69 | |
| 70 | | Reader | Writer | Configurable | Use Case | |
| 71 | |--------|--------|--------------|----------| |
| 72 | | `Load` | `Dump` | Yes | Single or multi-doc with options | |
| 73 | | `NewLoader` | `NewDumper` | Yes | Large files, continuous streams | |
| 74 | | `Unmarshal` | `Marshal` | No | Quick conversions, preset behavior | |
| 75 | | `NewDecoder` | `NewEncoder` | No | Multi-doc streams, preset behavior | |
| 76 | |
| 77 | ## Configurable API: Dump and Load |
| 78 | |
| 79 | Like Marshal/Unmarshal but with options support. |
| 80 | Perfect for single operations that need custom behavior. |
| 81 | |
| 82 | ### Dump |
| 83 | |
| 84 | Dump a single value with v4 defaults (2-space indent, compact): |
| 85 | |
| 86 | ```go |
| 87 | data, err := yaml.Dump(&config) |
| 88 | ``` |
| 89 | |
| 90 | With custom options: |
| 91 | |
| 92 | ```go |
| 93 | data, err := yaml.Dump(&config, yaml.WithIndent(4)) |
| 94 | ``` |
| 95 | |
| 96 | Dump multiple values as a multi-document stream using `WithAllDocuments()`: |
| 97 | |
| 98 | ```go |
| 99 | docs := []Config{config1, config2, config3} |
| 100 | data, err := yaml.Dump(docs, yaml.WithAllDocuments(), yaml.WithIndent(2)) |
| 101 | // Output: |
| 102 | // name: first |
| 103 | // --- |
| 104 | // name: second |
| 105 | // --- |
| 106 | // name: third |
| 107 | ``` |
| 108 | |
| 109 | ### Load |
| 110 | |
| 111 | Load a single document with options: |
| 112 | |
| 113 | ```go |
| 114 | var config Config |
| 115 | err := yaml.Load(yamlData, &config, yaml.WithKnownFields()) |
| 116 | ``` |
| 117 | |
| 118 | **Important:** `Load` requires exactly one document by default. |
| 119 | Zero documents or multiple documents will return an error. |
| 120 | |
| 121 | Strict validation catches typos: |
| 122 | |
| 123 | ```go |
| 124 | yamlData := []byte(` |
| 125 | name: myapp |
| 126 | prto: 8080 # typo! |
| 127 | `) |
| 128 | |
| 129 | var config Config |
| 130 | err := yaml.Load(yamlData, &config, yaml.WithKnownFields()) |
| 131 | // Error: field prto not found in type Config |
| 132 | ``` |
| 133 | |
| 134 | Load all documents from a multi-document stream using `WithAllDocuments()`: |
| 135 | |
| 136 | ```go |
| 137 | multiDoc := []byte(` |
| 138 | name: first |
| 139 | --- |
| 140 | name: second |
| 141 | --- |
| 142 | name: third |
| 143 | `) |
| 144 | |
| 145 | var docs []map[string]any |
| 146 | err := yaml.Load(multiDoc, &docs, yaml.WithAllDocuments()) |
| 147 | for i, doc := range docs { |
| 148 | fmt.Printf("Doc %d: %v\n", i, doc) |
| 149 | } |
| 150 | ``` |
| 151 | |
| 152 | With typed slices: |
| 153 | |
| 154 | ```go |
| 155 | var configs []Config |
| 156 | err := yaml.Load(multiDoc, &configs, yaml.WithAllDocuments()) |
| 157 | // Each document decoded as Config |
| 158 | ``` |
| 159 | |
| 160 | **When to use:** Need options but don't need streaming. |
| 161 | Config files, API responses, test data. |
| 162 | |
| 163 | ## Configurable Streaming API: NewDumper and NewLoader |
| 164 | |
| 165 | Full control over dumping/loading with streaming support and configurable |
| 166 | options. |
| 167 | Use for large files, network streams, or when you need to process documents one |
| 168 | at a time with custom configuration. |
| 169 | |
| 170 | ### NewDumper |
| 171 | |
| 172 | Create a dumper that writes to any `io.Writer`: |
| 173 | |
| 174 | ```go |
| 175 | file, _ := os.Create("output.yaml") |
| 176 | defer file.Close() |
| 177 | |
| 178 | dumper, err := yaml.NewDumper(file, yaml.WithIndent(2)) |
| 179 | if err != nil { |
| 180 | log.Fatal(err) |
| 181 | } |
| 182 | |
| 183 | // Dump multiple documents |
| 184 | dumper.Dump(&doc1) |
| 185 | dumper.Dump(&doc2) |
| 186 | dumper.Dump(&doc3) |
| 187 | |
| 188 | // Always close to flush remaining output |
| 189 | dumper.Close() |
| 190 | ``` |
| 191 | |
| 192 | Write to a buffer: |
| 193 | |
| 194 | ```go |
| 195 | var buf bytes.Buffer |
| 196 | dumper, _ := yaml.NewDumper(&buf, yaml.WithIndent(2)) |
| 197 | dumper.Dump(&config) |
| 198 | dumper.Close() |
| 199 | fmt.Println(buf.String()) |
| 200 | ``` |
| 201 | |
| 202 | **Note: `NewDumper` opens a write stream that must be closed with a call to |
| 203 | `Close()`. |
| 204 | This call can be deferred.** |
| 205 | |
| 206 | ### NewLoader |
| 207 | |
| 208 | Create a loader that reads from any `io.Reader`: |
| 209 | |
| 210 | ```go |
| 211 | file, _ := os.Open("config.yaml") |
| 212 | defer file.Close() |
| 213 | |
| 214 | loader, err := yaml.NewLoader(file, yaml.WithKnownFields()) |
| 215 | if err != nil { |
| 216 | log.Fatal(err) |
| 217 | } |
| 218 | |
| 219 | var config Config |
| 220 | if err := loader.Load(&config); err != nil { |
| 221 | log.Fatal(err) |
| 222 | } |
| 223 | ``` |
| 224 | |
| 225 | Process multi-document streams: |
| 226 | |
| 227 | ```go |
| 228 | loader, _ := yaml.NewLoader(reader) |
| 229 | |
| 230 | for { |
| 231 | var doc map[string]any |
| 232 | err := loader.Load(&doc) |
| 233 | if err == io.EOF { |
| 234 | break |
| 235 | } |
| 236 | if err != nil { |
| 237 | log.Fatal(err) |
| 238 | } |
| 239 | processDocument(doc) |
| 240 | } |
| 241 | ``` |
| 242 | |
| 243 | **When to use:** Large files, network streams, processing documents |
| 244 | incrementally, or when you need maximum control. |
| 245 | |
| 246 | ## Classic API: Marshal and Unmarshal |
| 247 | |
| 248 | Simple conversion with no options or streaming. |
| 249 | |
| 250 | **Note:** These functions use **v3 semantics** (4-space indent, non-compact |
| 251 | sequences) and **do not accept options**. |
| 252 | For new code in v4+, use `Dump` and `Load` instead, which offer the |
| 253 | same simplicity with full options control. |
| 254 | |
| 255 | ### Marshal |
| 256 | |
| 257 | ```go |
| 258 | import "go.yaml.in/yaml/v4" |
| 259 | |
| 260 | type Config struct { |
| 261 | Name string `yaml:"name"` |
| 262 | Port int `yaml:"port"` |
| 263 | Enabled bool `yaml:"enabled"` |
| 264 | } |
| 265 | |
| 266 | config := Config{Name: "myapp", Port: 8080, Enabled: true} |
| 267 | data, err := yaml.Marshal(&config) |
| 268 | // Output: |
| 269 | // name: myapp |
| 270 | // port: 8080 |
| 271 | // enabled: true |
| 272 | ``` |
| 273 | |
| 274 | **Equivalent using Dump with v3 semantics to match Marshal:** |
| 275 | |
| 276 | ```go |
| 277 | config := Config{Name: "myapp", Port: 8080, Enabled: true} |
| 278 | data, err := yaml.Dump(&config, yaml.WithV3Defaults()) |
| 279 | // Same output as Marshal (4-space indent, non-compact) |
| 280 | ``` |
| 281 | |
| 282 | ### Unmarshal |
| 283 | |
| 284 | ```go |
| 285 | yamlData := []byte(` |
| 286 | name: myapp |
| 287 | port: 8080 |
| 288 | enabled: true |
| 289 | `) |
| 290 | |
| 291 | var config Config |
| 292 | err := yaml.Unmarshal(yamlData, &config) |
| 293 | fmt.Println(config.Name) // "myapp" |
| 294 | ``` |
| 295 | |
| 296 | **Equivalent using Load with v3 semantics to match Unmarshal:** |
| 297 | |
| 298 | ```go |
| 299 | var config Config |
| 300 | err := yaml.Load(yamlData, &config, yaml.WithV3Defaults()) |
| 301 | fmt.Println(config.Name) // "myapp" |
| 302 | ``` |
| 303 | |
| 304 | **When to use:** Quick scripts, tests, simple config files where default |
| 305 | formatting is fine. |
| 306 | |
| 307 | ## Classic Streaming API: Encoder and Decoder |
| 308 | |
| 309 | For multi-document streams without needing options. |
| 310 | Simple functions for encoding/decoding streams. |
| 311 | |
| 312 | ### Encode |
| 313 | |
| 314 | Encode values to an `io.Writer`: |
| 315 | |
| 316 | ```go |
| 317 | file, _ := os.Create("output.yaml") |
| 318 | defer file.Close() |
| 319 | |
| 320 | encoder := yaml.NewEncoder(file) |
| 321 | encoder.Encode(&doc1) |
| 322 | encoder.Encode(&doc2) |
| 323 | encoder.Encode(&doc3) |
| 324 | encoder.Close() |
| 325 | ``` |
| 326 | |
| 327 | Each call to `Encode` writes a separate YAML document: |
| 328 | |
| 329 | ```yaml |
| 330 | name: first |
| 331 | --- |
| 332 | name: second |
| 333 | --- |
| 334 | name: third |
| 335 | ``` |
| 336 | |
| 337 | **Equivalent using NewDumper with v3 semantics to match Encoder:** |
| 338 | |
| 339 | ```go |
| 340 | file, _ := os.Create("output.yaml") |
| 341 | defer file.Close() |
| 342 | |
| 343 | dumper, _ := yaml.NewDumper(file, yaml.WithV3Defaults()) |
| 344 | dumper.Dump(&doc1) |
| 345 | dumper.Dump(&doc2) |
| 346 | dumper.Dump(&doc3) |
| 347 | dumper.Close() |
| 348 | // Same output as NewEncoder (4-space indent, non-compact) |
| 349 | ``` |
| 350 | |
| 351 | ### Decode |
| 352 | |
| 353 | Decode values from an `io.Reader`: |
| 354 | |
| 355 | ```go |
| 356 | file, _ := os.Open("config.yaml") |
| 357 | defer file.Close() |
| 358 | |
| 359 | decoder := yaml.NewDecoder(file) |
| 360 | |
| 361 | for { |
| 362 | var doc map[string]any |
| 363 | err := decoder.Decode(&doc) |
| 364 | if err == io.EOF { |
| 365 | break |
| 366 | } |
| 367 | if err != nil { |
| 368 | log.Fatal(err) |
| 369 | } |
| 370 | processDocument(doc) |
| 371 | } |
| 372 | ``` |
| 373 | |
| 374 | **Equivalent using NewLoader with v3 semantics to match Decoder:** |
| 375 | |
| 376 | ```go |
| 377 | file, _ := os.Open("config.yaml") |
| 378 | defer file.Close() |
| 379 | |
| 380 | loader, _ := yaml.NewLoader(file, yaml.WithV3Defaults()) |
| 381 | |
| 382 | for { |
| 383 | var doc map[string]any |
| 384 | err := loader.Load(&doc) |
| 385 | if err == io.EOF { |
| 386 | break |
| 387 | } |
| 388 | if err != nil { |
| 389 | log.Fatal(err) |
| 390 | } |
| 391 | processDocument(doc) |
| 392 | } |
| 393 | ``` |
| 394 | |
| 395 | **When to use:** Multi-document streams where default formatting is fine. |
| 396 | No need for custom indentation or validation options. |
| 397 | |
| 398 | ## Options System |
| 399 | |
| 400 | All flexible and streaming APIs accept options. |
| 401 | Options are applied left-to-right, with later options overriding earlier ones. |
| 402 | |
| 403 | ### Individual Options |
| 404 | |
| 405 | ```go |
| 406 | yaml.NewDumper(w, |
| 407 | yaml.WithIndent(2), // 2-space indentation |
| 408 | yaml.WithCompactSeqIndent(), // Compact list style (defaults to true) |
| 409 | yaml.WithLineWidth(120), // Wider lines |
| 410 | yaml.WithUnicode(false), // Escape Unicode (override default) |
| 411 | ) |
| 412 | |
| 413 | yaml.NewLoader(r, |
| 414 | yaml.WithKnownFields(), // Strict field checking (defaults to true) |
| 415 | yaml.WithSingleDocument(), // Only load first doc |
| 416 | yaml.WithUniqueKeys(), // Error on duplicate keys (defaults to true) |
| 417 | ) |
| 418 | ``` |
| 419 | |
| 420 | ### Version Presets |
| 421 | |
| 422 | Use preset options that match different go-yaml versions: |
| 423 | |
| 424 | ```go |
| 425 | // v2: 2-space indent, non-compact sequences |
| 426 | yaml.Dump(&config, yaml.WithV2Defaults()) |
| 427 | |
| 428 | // v3: 4-space indent, non-compact sequences |
| 429 | yaml.Dump(&config, yaml.WithV3Defaults()) |
| 430 | |
| 431 | // v4: 2-space indent, compact sequences (default) |
| 432 | yaml.Dump(&config, yaml.WithV4Defaults()) // or just yaml.Dump(&config) |
| 433 | ``` |
| 434 | |
| 435 | ### Combining Options |
| 436 | |
| 437 | Mix presets with individual overrides: |
| 438 | |
| 439 | ```go |
| 440 | // Start with v3, then override indent to 2 |
| 441 | yaml.NewDumper(w, |
| 442 | yaml.WithV3Defaults(), |
| 443 | yaml.WithIndent(2), // This wins |
| 444 | ) |
| 445 | ``` |
| 446 | |
| 447 | ### Loading Options from YAML |
| 448 | |
| 449 | Configure formatting via YAML files: |
| 450 | |
| 451 | ```go |
| 452 | configYAML := ` |
| 453 | indent: 3 |
| 454 | compact-seq-indent: true |
| 455 | known-fields: true |
| 456 | ` |
| 457 | |
| 458 | opts, err := yaml.OptsYAML(configYAML) |
| 459 | if err != nil { |
| 460 | log.Fatal(err) |
| 461 | } |
| 462 | |
| 463 | data, err := yaml.Dump(&config, opts) |
| 464 | ``` |
| 465 | |
| 466 | See [Options Guide](options.md) for complete option reference. |
| 467 | |
| 468 | ## Node-Level Load and Dump |
| 469 | |
| 470 | When working with the Node API directly, you can also use options through the |
| 471 | `Load()` and `Dump()` methods. |
| 472 | |
| 473 | ### Node.Load() - Load with Options |
| 474 | |
| 475 | The `Node.Load()` method is particularly useful inside custom `UnmarshalYAML` |
| 476 | implementations where you need to preserve options like `WithKnownFields()`. |
| 477 | |
| 478 | ```go |
| 479 | type Config struct { |
| 480 | Name string `yaml:"name"` |
| 481 | Port int `yaml:"port"` |
| 482 | } |
| 483 | |
| 484 | func (c *Config) UnmarshalYAML(node *yaml.Node) error { |
| 485 | type plain Config |
| 486 | // Use Load to preserve KnownFields option |
| 487 | return node.Load((*plain)(c), yaml.WithKnownFields()) |
| 488 | } |
| 489 | ``` |
| 490 | |
| 491 | **Solves Issue #460:** Before `node.Load()`, calling `node.Decode()` in custom |
| 492 | unmarshalers would create a new decoder without options, losing strict field |
| 493 | validation. |
| 494 | |
| 495 | **Usage example:** |
| 496 | |
| 497 | ```go |
| 498 | yamlData := []byte(` |
| 499 | name: myapp |
| 500 | port: 8080 |
| 501 | unknown: field # This will be caught! |
| 502 | `) |
| 503 | |
| 504 | var config Config |
| 505 | err := yaml.Unmarshal(yamlData, &config) |
| 506 | if err != nil { |
| 507 | fmt.Println("Error:", err) // Error: field unknown not found in type Config |
| 508 | } |
| 509 | ``` |
| 510 | |
| 511 | ### Node.Dump() - Dump with Options |
| 512 | |
| 513 | The `Node.Dump()` method lets you apply dumping options when building Node |
| 514 | trees programmatically: |
| 515 | |
| 516 | ```go |
| 517 | config := Config{Name: "myapp", Port: 8080} |
| 518 | |
| 519 | var node yaml.Node |
| 520 | err := node.Dump(&config, |
| 521 | yaml.WithIndent(2), |
| 522 | yaml.WithExplicitStart(), |
| 523 | ) |
| 524 | |
| 525 | // Now marshal the node to YAML |
| 526 | data, _ := yaml.Marshal(&node) |
| 527 | fmt.Println(string(data)) |
| 528 | // Output: |
| 529 | // --- |
| 530 | // name: myapp |
| 531 | // port: 8080 |
| 532 | ``` |
| 533 | |
| 534 | **When to use:** |
| 535 | - Custom unmarshalers that need strict validation (`node.Load()`) |
| 536 | - Building Node trees with specific formatting (`node.Dump()`) |
| 537 | - Programmatic YAML manipulation with options |
| 538 | - Preserving options through the full load/dump pipeline |
| 539 | |
| 540 | ## Examples |
| 541 | |
| 542 | ### Example 1: Config File with Validation |
| 543 | |
| 544 | ```go |
| 545 | func LoadConfig(filename string) (*Config, error) { |
| 546 | data, err := os.ReadFile(filename) |
| 547 | if err != nil { |
| 548 | return nil, err |
| 549 | } |
| 550 | |
| 551 | var config Config |
| 552 | err = yaml.Load(data, &config, |
| 553 | yaml.WithKnownFields(), // Catch typos (defaults to true) |
| 554 | ) |
| 555 | return &config, err |
| 556 | } |
| 557 | ``` |
| 558 | |
| 559 | ### Example 2: Generate CI/CD Config |
| 560 | |
| 561 | ```go |
| 562 | func GeneratePipeline(stages []Stage) ([]byte, error) { |
| 563 | return yaml.Dump(&Pipeline{Stages: stages}, |
| 564 | yaml.WithIndent(2), // CI systems prefer 2-space |
| 565 | ) |
| 566 | } |
| 567 | ``` |
| 568 | |
| 569 | ### Example 3: Process Log Stream |
| 570 | |
| 571 | ```go |
| 572 | func ProcessYAMLLogs(reader io.Reader) error { |
| 573 | loader, _ := yaml.NewLoader(reader) |
| 574 | |
| 575 | for { |
| 576 | var entry LogEntry |
| 577 | err := loader.Load(&entry) |
| 578 | if err == io.EOF { |
| 579 | return nil |
| 580 | } |
| 581 | if err != nil { |
| 582 | return err |
| 583 | } |
| 584 | handleLogEntry(entry) |
| 585 | } |
| 586 | } |
| 587 | ``` |
| 588 | |
| 589 | ### Example 4: Merge Multiple Configs |
| 590 | |
| 591 | ```go |
| 592 | func MergeConfigs(files []string) ([]byte, error) { |
| 593 | var allDocs []any |
| 594 | |
| 595 | for _, f := range files { |
| 596 | data, _ := os.ReadFile(f) |
| 597 | var docs []any |
| 598 | _ = yaml.Load(data, &docs, yaml.WithAllDocuments()) |
| 599 | allDocs = append(allDocs, docs...) |
| 600 | } |
| 601 | |
| 602 | return yaml.Dump(allDocs, yaml.WithAllDocuments(), yaml.WithIndent(2)) |
| 603 | } |
| 604 | ``` |
| 605 | |
| 606 | ## See Also |
| 607 | |
| 608 | - [Options Guide](options.md) - Complete option reference |
| 609 | - [API Documentation](https://pkg.go.dev/go.yaml.in/yaml/v4) - Full API |
| 610 | reference |