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

Parsing slice data to map failed #435

Closed
dong50252409 opened this issue Jan 7, 2025 · 2 comments
Closed

Parsing slice data to map failed #435

dong50252409 opened this issue Jan 7, 2025 · 2 comments

Comments

@dong50252409
Copy link

dong50252409 commented Jan 7, 2025

I want to map the data to the collect structure when parsing the ImportExtension field, so that I can quickly determine whether the table is supported at runtime. Unfortunately, I have tried a lot of methods and cannot call back the UnmarshalText method during parsing. What should I do? I can't parse the data through the UnmarshalTOML implementation interface because I actually have a lot of configuration

Example:

package main

import (
	"github.com/BurntSushi/toml"
	"log"
)

type collect struct {
	Set map[string]any
}

type contacts struct {
	Source             string
	ImportExtension    collect
}

func (c *collect) UnmarshalText(v []byte) error {
	// It won't be called here
	return nil
}

func main() {
	blob := `
		source = "./samples/"
		import_extension = ["csv", "xlsx"]
	`
	var c contacts
	_, err := toml.Decode(blob, &c)
	if err != nil {
		log.Fatal(err)
	}

}
@qdongxu
Copy link

qdongxu commented Jan 11, 2025

What is the X problem you want to resolve? It's unusual to request to parse a slice into a map.

@arp242
Copy link
Collaborator

arp242 commented Feb 18, 2025

You need to use struct tags to map the ImportExtension field to the import_extension value.

UnmarshalText is only called for strings, not arrays. You want UnmarshalTOML.

Putting that together:

package main

import (
	"fmt"

	"github.com/BurntSushi/toml"
)

type contacts struct {
	Source          string  `toml:"source"`
	ImportExtension collect `toml:"import_extension"`
}

type collect struct {
	Set map[string]any
}

func (c *collect) UnmarshalTOML(v any) error {
	fmt.Printf("UnmarshalTOML: %#v\n", v)
	return nil
}

func main() {
	var c contacts
	_, err := toml.Decode(`
		source = "./samples/"
		import_extension = ["csv", "xlsx"]
	`, &c)
	fmt.Println(err)
	fmt.Println(c)
}

Outputs:

UnmarshalTOML: []interface {}{"csv", "xlsx"}
<nil>
{./samples/ {map[]}}

@arp242 arp242 closed this as completed Feb 18, 2025
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

3 participants