mapstructure icon indicating copy to clipboard operation
mapstructure copied to clipboard

Omitempty fields

Open guillermo-menjivar opened this issue 4 years ago • 2 comments

Thank you for this project, I am looking for verification on an assumption I have when it comes to the omitempty flag in mapstructure.

Assumption: I expect any property that has the omitempty flag would be "omitted" from the map that is populated by mapstructure. I reference this test https://github.com/mitchellh/mapstructure/blob/07998cfd7ab2f7f7e5ddce402c4edf38317451eb/mapstructure_examples_test.go#L255 however, this test has no assertions but rather a comment of what it "should" be without validation. I want to make sure mapstructure "should not" be returning fields that are flagged with omitted. If so I am willing to send a PR, but want to make sure that I am understanding the library correctly.

I ran the following code:

package main

import (
        "fmt"

        "github.com/mitchellh/mapstructure"
)

type Job struct {
        Title string `mapstructure:"title,omitempty"`
}

type Person struct {
        Name string `mapstructure:"name"`
        Age  *int   `mapstructure:"age,omitempty"`
        *Job `mapstructure:",omitempty"`
}

func main() {
        m := &map[string]interface{}{}
        p := Person{Name: "rockets"}
        err := mapstructure.Decode(&p, m)

        if err != nil {
                fmt.Println("received an error while decoding", err)
                return
        }
        fmt.Println(m)
}

// returns: &map[Job:<nil> age:<nil> name:rockets]

guillermo-menjivar avatar Jan 25 '21 19:01 guillermo-menjivar

check out your mapstructure version >= 1.3.0 #145

chenjisuan avatar Jan 27 '22 07:01 chenjisuan

Yes if you write a test and make a PR, I will merge the fix. This looks like a bug to me.

mitchellh avatar Apr 20 '22 22:04 mitchellh