Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
zhyee opened this issue Jan 1, 2024 · 1 comment

Comments

@zhyee
Copy link

zhyee commented Jan 1, 2024

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
Copy link

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants