JSON presence detection using encoding/json/v2. Supports omitted, null, empty, and valued field states.
Requires GOEXPERIMENT=jsonv2. See http://go.dev/blog/jsonv2-exp
type User struct {
Name optional.Field[string] `json:"name"`
Age optional.Field[*int] `json:"age"`
}
var user User
json.Unmarshal([]byte(`{"name": "Alice"}`), &user)
fmt.Println(user.Name.Present) // true
fmt.Println(user.Age.Present) // falseYou might prefer to copy this code into your own repository rather than taking on this dependency:
type Optional[T any] struct {
Value T
Present bool
}
func (o *Optional[T]) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
if err := json.UnmarshalDecode(dec, &o.Value); err != nil {
return err
}
o.Present = true
return nil
}