Skip to content

Decode with embedded struct wrong set value into child struct #81

@alingse

Description

@alingse

show case

when call DecodeToData[B] the "version": "dfg" should not decode into B.A.Version field, it should only set into B.Version

package main

import (
	"fmt"

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

func DecodeToData[T any](input []any) ([]T, error) {
	var result []T
	decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
		WeaklyTypedInput: true,
		Squash:           true,
		Result:           &result,
		TagName:          "json",
	})
	if err != nil {
		return nil, err
	}
	err = decoder.Decode(input)
	if err != nil {
		return nil, err
	}
	return result, nil
}

type A struct {
	ObjType string `json:"obj_type"`
	ObjID   int64  `json:"obj_id"`
	Version int    `json:"version"`
}
type B struct {
	Version string `json:"version"`
	A
}

func main() {
	var input = []any{
		map[string]any{
			"obj_type": "a",
			"obj_id":   1,
			"version":  "1",
		},
		map[string]any{
			"obj_type": "b",
			"obj_id":   2,
			"version":  "defg",
		},
	}
	result, err := DecodeToData[A](input)
	fmt.Println("result1 ", result, err)

	result2, err2 := DecodeToData[B](input)
	fmt.Println("result2 ", result2, err2)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions