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

Invalid json will be unmarshal into a wrong result without throw error #1045

Open
dayeguilaiye opened this issue Aug 30, 2024 · 0 comments
Open

Comments

@dayeguilaiye
Copy link

I have a struct like below:

{
	"classroom": {
		"students": [
			"name": John,
			"scores": A,
		]
	}
}

The content in students is wrong, it missed a {} to wrap the name and score, which cause this string is not actually a valid json string.

but when I unmarshal with yaml.Unmarshal, no error is returned, and the result seem very weird. This is a simple example to reproduce:

type Student struct {
	Name   string `json:"name"`
	Scores string `json:"scores"`
}

type Classroom struct {
	Students []Student `json:"students"`
}

type School struct {
	Classroom Classroom `json:"classroom"`
}

func TestName(t *testing.T) {
	wrongInput := `{
	"classroom": {
		"students": [
			"name": John,
			"scores": A,
		]
	}
}`
	c := new(School)
	err := yaml.Unmarshal([]byte(wrongInput), c)
	fmt.Println(err)
	fmt.Printf("%+v", c)
}

output is:

<nil>
&{Classroom:{Students:[{Name:John Scores:} {Name: Scores:A}]}}

The result is there are two students in this classroom.

The most important question is why there is no error returned?

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

1 participant