Default values when unmarshal json in go

go

If we want to unmarshal a json into a struct, and we want to have default values if a value is absent in the json, the following code can be used:

type LogEndpoint struct {
    MaxLogLevel int `json:"max_log_level"`
}
func (o *LogEndpoint) UnmarshalJSON(text []byte) error {
    type defaults LogEndpoint
    
    opts := defaults{
     MaxLogLevel: 5,
    }
    if err := json.Unmarshal(text, &opts); err != nil {
     return err
    }
    *o = LogEndpoint(opts)
    return nil
}

The code provides a method called UnmarshalJSON that belongs to a struct called LogEndpoint. This method is used to deserialize JSON data into an instance of the LogEndpoint struct.

The method starts by defining a new type called defaults, which is an alias of the LogEndpoint struct. This new type is used to define default values for the LogEndpoint struct’s fields.

The go specification tells us: A defined type may have methods associated with it. It does not inherit any methods bound to the given type, but the method set of an interface type or of elements of a composite type remains unchanged...

This gives us the possibility to call json.Unmarshal on the opts variable, and not ending in a stackoverflow.

The opts variable is then initialized as an instance of the defaults struct, with a default value for MaxLogLevel set to 5.

The json.Unmarshal only sets the value of MaxLogLevel if it is present in the JSON data. If the MaxLogLevel field is missing from the JSON data, the default value of 5 will remain untouched.

In summary, the UnmarshalJSON method provided is a simple way to deserialize JSON data into a LogEndpoint struct, with default values provided for any missing fields. This method can be useful in situations where you want to ensure that all fields of a struct are properly initialized, even if some of them are not present in the JSON data.