Пример
sigs.k8s.io/yaml v1.6.0: sigs.k8s.io/yaml Unmarshal and Marshal ignore custom UnmarshalYAML and MarshalYAML methods, executing only encoding/json.Unmarshaler and encoding/json.Marshaler implementations due to intermediate JSON conversion.
Проверенный пример — golang sigs.k8s.io/yaml v1.6.0: sigs.k8s.io/yaml Unmarshal and Marshal ignore custom UnmarshalYAML and MarshalYAML methods, executing…
sha256:b6f988c23bf960eb73bd32c2f21ec82feba1b52021baad975f2b1fe2fb5ee355
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 3
- Ключи подписи, собравшие его
- 3
Заявленная среда
go linux x64 go go go
Среды запусков проверки
| Окружение | Контракт | Этапы | Запуск |
|---|---|---|---|
| go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-17 |
| go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-18 |
| go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f… |
2026-09-08 |
Кейс
HOW- Цель
- sigs.k8s.io/yaml Unmarshal and Marshal ignore custom UnmarshalYAML and MarshalYAML methods, executing only encoding/json.Unmarshaler and encoding/json.Marshaler implementations due to intermediate JSON conversion.
- Пакеты
- Символы
-
- yaml.Unmarshal
- yaml.Marshal
- Окружение
- go
- Создан
- 2026-08-17T17:35:29Z
Контракт
- yaml.Unmarshal and yaml.Marshal bypass custom UnmarshalYAML and MarshalYAML methods on Go types, leaving UnmarshalYAML uncalled and falling back to json.Unmarshaler or standard JSON reflection.
- yaml.Unmarshal executes custom UnmarshalJSON methods on target types after converting YAML input to JSON.
- yaml.Marshal executes custom MarshalJSON methods on source types and converts the resulting JSON bytes into YAML output.
Файлы
- NOTES.md
- csx.json
- go.mod
- go.sum
- yaml_test.go
Исходный код
# sigs.k8s.io/yaml Custom Interface Handling
## Prior Known Solutions
Querying known solutions for `sigs.k8s.io/yaml` returned existing samples covering:
- Overwriting duplicate mapping keys silently during `Unmarshal`
- `json:` struct tags taking precedence while `yaml:` tags are ignored
- Accepting unknown struct fields by default without returning errors
- Preserving 64-bit integer precision via `JSONOpt` `UseNumber`
This sample investigates how `sigs.k8s.io/yaml` handles custom marshaling and unmarshaling interfaces.
## Pinned Release
- `sigs.k8s.io/yaml v1.6.0`
## Observed Behaviour
`sigs.k8s.io/yaml` performs YAML processing by converting YAML into an intermediate JSON representation and delegating unmarshaling to Go's standard `encoding/json` package. Symmetrically, `yaml.Marshal` delegates encoding to `encoding/json.Marshal` before converting the resulting JSON into YAML.
Because data transformation is driven by Go's standard JSON library:
1. `yaml.Unmarshal` completely bypasses `UnmarshalYAML(unmarshal func(interface{}) error) error` (`yaml.Unmarshaler`). It only executes `UnmarshalJSON([]byte) error` (`encoding/json.Unmarshaler`).
2. `yaml.Marshal` completely bypasses `MarshalYAML() (interface{}, error)` (`yaml.Marshaler`). It only executes `MarshalJSON() ([]byte, error)` (`encoding/json.Marshaler`).
## Failure Mode
When migrating code from direct YAML packages (such as `gopkg.in/yaml.v2` or `gopkg.in/yaml.v3`) to `sigs.k8s.io/yaml`:
- Types with custom `UnmarshalYAML` logic fail silently with a green build. `yaml.Unmarshal` ignores the hook and falls back to standard JSON struct reflection, leaving custom parsed fields unpopulated or zero-valued.
- Types with custom `MarshalYAML` logic fail silently with a green build. `yaml.Marshal` ignores the hook and serializes the raw struct fields through JSON reflection before emitting YAML.
- To provide custom serialization hooks when using `sigs.k8s.io/yaml`, types must implement `UnmarshalJSON` and `MarshalJSON`.
{"case":{"believed":"A YAML parsing and serialization library invokes custom UnmarshalYAML and MarshalYAML hook methods implemented on Go types when decoding and encoding YAML documents.","caseId":"case:sha256:d7f710c4e6c260e4f1b30a0a3d3639b9717a0bd8e961fd826f39f93535be0bcd","contract":["yaml.Unmarshal and yaml.Marshal bypass custom UnmarshalYAML and MarshalYAML methods on Go types, leaving UnmarshalYAML uncalled and falling back to json.Unmarshaler or standard JSON reflection.","yaml.Unmarshal executes custom UnmarshalJSON methods on target types after converting YAML input to JSON.","yaml.Marshal executes custom MarshalJSON methods on source types and converts the resulting JSON bytes into YAML output."],"goal":"sigs.k8s.io/yaml Unmarshal and Marshal ignore custom UnmarshalYAML and MarshalYAML methods, executing only encoding/json.Unmarshaler and encoding/json.Marshaler implementations due to intermediate JSON conversion.","kind":"HOW","packages":["pkg:golang/sigs.k8s.io/yaml@1.6.0"],"schemaVersion":1,"symbols":["yaml.Unmarshal","yaml.Marshal"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/sigs.k8s.io/yaml@1.6.0"],"schemaVersion":1,"symbols":["yaml.Unmarshal","yaml.Marshal"],"verifierAdapter":"golang@1"}
module sample
go 1.26.5
require sigs.k8s.io/yaml v1.6.0
require go.yaml.in/yaml/v2 v2.4.2 // indirect
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
go.yaml.in/yaml/v3 v3.0.3 h1:bXOww4E/J3f66rav3pX3m8w6jDE4knZjGOw8b5Y6iNE=
go.yaml.in/yaml/v3 v3.0.3/go.mod h1:tBHosrYAkRZjRAOREWbDnBXUf08JOwYq++0QNwQiWzI=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs=
sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4=
package sample
import (
"encoding/json"
"strings"
"testing"
"sigs.k8s.io/yaml"
)
// CustomYamlType implements the yaml.Unmarshaler and yaml.Marshaler interfaces
// typically used by yaml.v2 / yaml.v3.
type CustomYamlType struct {
Value string
YamlHookCalled bool
}
func (c *CustomYamlType) UnmarshalYAML(unmarshal func(interface{}) error) error {
c.YamlHookCalled = true
var raw string
if err := unmarshal(&raw); err != nil {
return err
}
c.Value = "from-yaml-unmarshaler:" + raw
return nil
}
func (c CustomYamlType) MarshalYAML() (interface{}, error) {
return "custom-yaml-output:" + c.Value, nil
}
// CustomJsonType implements encoding/json.Unmarshaler and encoding/json.Marshaler.
type CustomJsonType struct {
Value string
JsonHookCalled bool
}
func (c *CustomJsonType) UnmarshalJSON(data []byte) error {
c.JsonHookCalled = true
var raw string
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
c.Value = "from-json-unmarshaler:" + raw
return nil
}
func (c CustomJsonType) MarshalJSON() ([]byte, error) {
return json.Marshal("custom-json-output:" + c.Value)
}
func TestCustomInterfaces(t *testing.T) {
// 1. Unmarshal with UnmarshalYAML vs UnmarshalJSON:
// sigs.k8s.io/yaml converts YAML to JSON first and calls json.Unmarshal.
// Therefore, UnmarshalYAML is completely ignored.
var yObj CustomYamlType
err := yaml.Unmarshal([]byte("Value: hello"), &yObj)
if err != nil {
t.Fatalf("unexpected unmarshal error: %v", err)
}
if yObj.YamlHookCalled {
t.Fatalf("expected UnmarshalYAML hook NOT to be called, but it was")
}
if yObj.Value != "hello" {
t.Fatalf("expected Value to be 'hello' from json reflection, got %q", yObj.Value)
}
// Conversely, UnmarshalJSON is invoked when unmarshaling YAML.
var jObj CustomJsonType
err = yaml.Unmarshal([]byte("hello"), &jObj)
if err != nil {
t.Fatalf("unexpected unmarshal error: %v", err)
}
if !jObj.JsonHookCalled {
t.Fatalf("expected UnmarshalJSON hook to be called, but it was not")
}
if jObj.Value != "from-json-unmarshaler:hello" {
t.Fatalf("expected Value to be %q, got %q", "from-json-unmarshaler:hello", jObj.Value)
}
// 2. Marshal with MarshalYAML vs MarshalJSON:
// sigs.k8s.io/yaml calls json.Marshal first, which ignores MarshalYAML.
yOut, err := yaml.Marshal(CustomYamlType{Value: "sample-val"})
if err != nil {
t.Fatalf("unexpected marshal error: %v", err)
}
if strings.Contains(string(yOut), "custom-yaml-output") {
t.Fatalf("expected MarshalYAML NOT to be called, but found custom output: %s", string(yOut))
}
if !strings.Contains(string(yOut), "Value: sample-val") {
t.Fatalf("expected standard struct field serialization, got: %s", string(yOut))
}
// MarshalJSON is called and its JSON result is converted to YAML.
jOut, err := yaml.Marshal(CustomJsonType{Value: "sample-val"})
if err != nil {
t.Fatalf("unexpected marshal error: %v", err)
}
expectedYaml := "custom-json-output:sample-val\n"
if string(jOut) != expectedYaml {
t.Fatalf("expected MarshalJSON output converted to YAML %q, got %q", expectedYaml, string(jOut))
}
}