Skip to content
/ optional Public

Generic optional fields for JSON presence detection using encoding/json/v2. Supports omitted, null, empty, and valued field states.

License

Notifications You must be signed in to change notification settings

bmon/optional

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go Reference

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)     // false

You 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
}

About

Generic optional fields for JSON presence detection using encoding/json/v2. Supports omitted, null, empty, and valued field states.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages