Skip to content

Int map keys incorrectly marshaled as string #680

Open
@herczegzsolt

Description

@herczegzsolt

Describe the bug
Whenever go-yaml encounters a map with int key, it marshals it like it had a string key. This makes it incompatible with itself.

To Reproduce

This is very easy to reproduce with even a simple map[int]string.

import (
	"fmt"

	"github.com/goccy/go-yaml"
)

func main() {
	f := make(map[int]string)
	f[1] = "one"
	f[3] = "three"
	enc, _ := yaml.Marshal(f)
	fmt.Printf("%s\n", enc)
	var g map[int]string
	err := yaml.Unmarshal(enc, &g)
	fmt.Printf("%v\n", err)
	fmt.Printf("%v\n", g)
}

Playground link is here: https://go.dev/play/p/OWQPOj_ECBP

Expected behavior
I expect that map[int]string would be encoded as 1: "one" not as "1":"one"
I also expect that yaml.Unmarshal can handle without errors whatever output yaml.Marshal has created.

If you do nothing else than replace the import from github.com/goccy/go-yaml to gopkg.in/yaml.v3, the example code would work as expected.

Screenshots
Please run the code on Go Playground :-)

Version Variables

  • Go version: 1.24.1
  • go-yaml's Version: v1.15.13
    But I think it affects all available versions.

Additional context
I tried to workaround this by using a MarshalYAML()([]byte,error) method on the map key type, but even if I return the byte slice directly, it is converted to string.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions