Skip to content

Json fields with hypen (-) are not decoded properly #83

Open

Description

@fedulovivan

Json fields with hypen (-) are not decoded properly (BTW same for original mitchellh/mapstructure).

Minimal reproduction code (tried with go 1.22.5, 1.24)

package main
import (
	"fmt"

	"github.com/go-viper/mapstructure/v2"
)
type Out struct {
	Foo    int `json:"foo"`
	BarBaz int `json:"bar-baz"`
}
func main() {
	in := make(map[string]any)
	in["foo"] = 1
	in["bar-baz"] = 2
	out := new(Out)
	mapstructure.Decode(in, out)
	fmt.Printf("%+v", out)
}

Actual
&{Foo:1 BarBaz:0}
Expected
&{Foo:1 BarBaz:2}

Activity

  1. changed the title [-]Json fields with hypen (-) are not encoded properly[/-] [+]Json fields with hypen (-) are not decoded properly[/+] on Mar 25, 2025
  2. fedulovivan commented on Mar 27, 2025

    @fedulovivan
    Author

    BTW, if I replace mapstructure.Decode with following workaround

    func mapstructureDecode(in any, out any) error {
    	jsonData, err := json.Marshal(in)
    	if err != nil {
    		return err
    	}
    	err = json.Unmarshal(jsonData, out)
    	if err != nil {
    		return err
    	}
    	return nil
    }

    everything works as intended

  3. ddelpero commented on Mar 31, 2025

    @ddelpero

    Have you tried mapstructure:"bar-baz" instead of json? I assumed the json tags would also work, but there is an example in the documentation that uses mapstructure.

  4. fedulovivan commented on Apr 1, 2025

    @fedulovivan
    Author

    @ddelpero Thank you, yep I can confirm replacing "json" with "mapstructure" fixes the issue. Anyway this looks like a bug.

  5. ddelpero commented on Apr 3, 2025

    @ddelpero

    You can use a custom decoder config:

    config := mapstructure.DecoderConfig{
       TagName: "json",
       Result:  &out}
    
    decoder, err := mapstructure.NewDecoder(&config)
    if err != nil {
       fmt.Println("Decoder config error: ", err)
    }
    err = decoder.Decode(in)
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