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

How to customize the values mapped to the map? #35

Open
baagod opened this issue Jul 15, 2024 · 2 comments
Open

How to customize the values mapped to the map? #35

baagod opened this issue Jul 15, 2024 · 2 comments

Comments

@baagod
Copy link

baagod commented Jul 15, 2024

package main

import (
	"fmt"
	"reflect"
	"time"

	"github.com/go-viper/mapstructure/v2"
)

type Person struct {
	Time time.Time `json:"time"`
	Name string    `json:"name"`
}

func main() {
	result := map[string]any{}
	input := Person{time.Now(), "testName"}

	decoder, errDecoder := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
		DecodeHook: func(f reflect.Type, t reflect.Type, data any) (any, error) {
			if value, ok := data.(*time.Time); ok {
				return value.Format(time.DateTime), nil
			}
			return data, nil
		},
		Result:  &result,
		TagName: "json",
	})

	if errDecoder != nil {
		panic(errDecoder)
	}

	err := decoder.Decode(input)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%#v\n", result)
}

Here, I want to add the 'time' of the structure Convert the Time type to a string in the 'result', but it cannot be done. report errors:

panic: 'time' expected a map, got 'string'

goroutine 1 [running]:
main.main()
	C:/Users/78081/AppData/Roaming/JetBrains/GoLand2024.1/scratches/scratch.go:37 +0x1a6

Is there a solution?

@MrDan4es
Copy link

MrDan4es commented Sep 1, 2024

@baagod
Copy link
Author

baagod commented Sep 1, 2024

@MrDan4es I pulled a request #43, not sure if it can be merged, I'm currently using my own fork of the:
go get github.com/baagod/mapstructure/v2@b1

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