Skip to content

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

Open

Description

@baagod
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?

Activity

  1. baagod commented on Sep 1, 2024

    @baagod
    Author

    @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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions