Open zhyee opened 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.
Hi. You can use yaml:",inline" for embedded structures.
yaml:",inline"
https://pkg.go.dev/gopkg.in/yaml.v3#example-Unmarshal-Embedded
Take a look at the code below:
the output:
"encoding/json" can set field value of embeded struct,but yaml not.