Skip to content
This repository was archived by the owner on Jul 22, 2024. It is now read-only.
This repository was archived by the owner on Jul 22, 2024. It is now read-only.

Encode a struct with ",remain" back to a map? #279

Description

@kszafran

I have a use case where I need to decode a JSON, where I care only about a few fields, change it here and there, and then serialize it back to JSON. However, the remainder values seem to get serialized into an empty "" JSON field. This is my code:

func TestDecodeEncode(t *testing.T) {
	var stuff struct {
		Field string                 `mapstructure:"field"`
		Other map[string]interface{} `mapstructure:",remain"`
	}
	err := Decode(strings.NewReader(`{
		"field": "hello",
		"anotherField": "world"
	}`), &stuff)
	if err != nil {
		panic(err)
	}
	bs, err := Encode(stuff)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", bs)
}

func Decode(r io.Reader, result interface{}) error {
	var m interface{}
	if err := json.NewDecoder(r).Decode(&m); err != nil {
		return err
	}
	return mapstructure.Decode(m, result)
}

func Encode(v interface{}) ([]byte, error) {
	var m map[string]interface{}
	if err := mapstructure.Decode(v, &m); err != nil {
		return nil, err
	}
	return json.Marshal(m)
}

And the output is:

{"":{"anotherField":"world"},"field":"hello"}

Am I missing some configuration option or is remain just not supported when encoding a struct into a map?

I'm using mapstructure version v1.4.3.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions