optional

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2025 License: MIT Imports: 2 Imported by: 0

README

optional

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

Requires GOEXPERIMENT=jsonv2.

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 take on a 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
}

Documentation

Overview

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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Field

type Field[T any] struct {
	Value   T    // The field's value
	Present bool // Whether the field was present in JSON
}

Field represents an optional field that can distinguish between omitted, null, empty, and valued states. The Present field indicates whether the field was present in the JSON input.

func (*Field[T]) UnmarshalJSONFrom

func (o *Field[T]) UnmarshalJSONFrom(dec *jsontext.Decoder) error

UnmarshalJSONFrom implements json.UnmarshalerV2

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL