go-yaml / yaml

YAML support for the Go language.
Other
6.85k stars 1.05k forks source link

Different behaviors between this library and standard encoding/json when unmarshal yaml to a struct embedded with other structs #1012

Open zhyee opened 9 months ago

zhyee commented 9 months ago

Take a look at the code below:

package main

import (
    "encoding/json"
    "fmt"
    "log"

    "gopkg.in/yaml.v3"
)

type Base struct {
    Name string `json:"name" yaml:"name"`
}

type Foo struct {
    Base
    FooName string `json:"foo_name" yaml:"foo_name"`
}

type Bar struct {
    Base
    BarName string `json:"bar_name" yaml:"bar_name"`
}

var jsonTxt = `{
    "name": "base",
    "foo_name": "foobar"
}`

var yamlTxt = `
name: base
bar_name: foobar
`

func main() {
    var (
        foo Foo
        bar Bar
    )
    if err := json.Unmarshal([]byte(jsonTxt), &foo); err != nil {
        log.Fatal(err)
    }

    if err := yaml.Unmarshal([]byte(yamlTxt), &bar); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("foo.Name in json: %q, foo.FooName in json: %q\n", foo.Name, foo.FooName)
    fmt.Printf("bar.Name in yaml: %q, bar.BarName in yaml; %q\n", bar.Name, bar.BarName)
}

the output:

foo.Name in json: "base", foo.FooName in json: "foobar"
bar.Name in yaml: "", bar.BarName in yaml; "foobar"

"encoding/json" can set field value of embeded struct,but yaml not.

bogushevich commented 5 months ago

Hi. You can use yaml:",inline" for embedded structures.

https://pkg.go.dev/gopkg.in/yaml.v3#example-Unmarshal-Embedded