Skip to content

Instantly share code, notes, and snippets.

@dwburke
Created June 29, 2020 15:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dwburke/ad02125c489a03b0fd03da1ec3dbe085 to your computer and use it in GitHub Desktop.
Save dwburke/ad02125c489a03b0fd03da1ec3dbe085 to your computer and use it in GitHub Desktop.
Default values when unmarshalling json in go
package foo
type Foo struct {
Field string `json:"field"`
}
// UnmarshalJSON is the implementation of the json.Unmarshaler interface.
func (t *Foo) UnmarshalJSON(data []byte) error {
type innerFoo Foo
inner := &innerFoo{
Field: "default value",
}
if err := json.Unmarshal(data, inner); err != nil {
return err
}
*t = Foo(*inner)
return nil
}
@dwburke
Copy link
Author

dwburke commented Jul 7, 2021

example to set default values on a struct when unmarshing json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment