Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion internal/libyaml/structmeta.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,11 @@ func getStructInfo(st reflect.Type) (*structInfo, error) {
if len(fields) > 1 {
for _, flag := range fields[1:] {
switch flag {
case "omitempty":
case "omitempty", "omitzero":
// omitzero is Go 1.24's encoding/json flag. yaml's
// omitempty already drops zero values (including structs),
// so treat omitzero as the same to avoid panicking on
// structs that share tags with json.
info.OmitEmpty = true
case "flow":
info.Flow = true
Expand Down
45 changes: 45 additions & 0 deletions omitzero_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright 2025 The go-yaml Project Contributors
// SPDX-License-Identifier: Apache-2.0

package yaml_test

import (
"testing"

"go.yaml.in/yaml/v4"
)

func TestUnmarshalOmitZeroFlag(t *testing.T) {
type T struct {
A string `yaml:"a,omitzero"`
B int `yaml:"b,omitzero"`
}
var v T
if err := yaml.Unmarshal([]byte("a: hi\nb: 2\n"), &v); err != nil {
t.Fatal(err)
}
if v.A != "hi" || v.B != 2 {
t.Fatalf("got %+v", v)
}
}

func TestMarshalOmitZeroFlag(t *testing.T) {
type T struct {
A string `yaml:"a,omitzero"`
B int `yaml:"b,omitzero"`
}
out, err := yaml.Marshal(T{})
if err != nil {
t.Fatal(err)
}
if string(out) != "{}\n" {
t.Fatalf("got %q", out)
}
out, err = yaml.Marshal(T{A: "hi", B: 2})
if err != nil {
t.Fatal(err)
}
if string(out) != "a: hi\nb: 2\n" {
t.Fatalf("got %q", out)
}
}