jsonhelpers

package
v1.45.4 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package jsonhelpers provides helper functions for JSON marshaling and unmarshaling with support for extension fields (x-* properties) in OpenAPI specifications.

This package reduces boilerplate code in custom JSON marshal/unmarshal implementations while preserving extension fields that are not part of the OpenAPI schema.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractExtensions added in v1.28.4

func ExtractExtensions(data []byte) map[string]any

ExtractExtensions extracts specification extension fields (x-* properties) from JSON data. This is the common pattern used in all UnmarshalJSON methods to capture extension fields.

Returns nil if no extensions are found or if the data cannot be parsed. This function never returns an error - parsing failures result in nil extensions.

Example:

func (c *Contact) UnmarshalJSON(data []byte) error {
    type Alias Contact
    if err := json.Unmarshal(data, (*Alias)(c)); err != nil {
        return err
    }
    c.Extra = jsonhelpers.ExtractExtensions(data)
    return nil
}

func GetAny

func GetAny(m map[string]any, key string) any

GetAny safely extracts a value of any type from a map and removes it. Returns nil if the key doesn't exist.

func GetBool

func GetBool(m map[string]any, key string) bool

GetBool safely extracts a boolean value from a map and removes it. Returns false if the key doesn't exist or value is not a boolean.

func GetFloat64

func GetFloat64(m map[string]any, key string) float64

GetFloat64 safely extracts a float64 value from a map and removes it. Returns 0.0 if the key doesn't exist or value is not a number.

func GetInt

func GetInt(m map[string]any, key string) int

GetInt safely extracts an integer value from a map and removes it. Returns 0 if the key doesn't exist or value is not a number. JSON numbers are unmarshaled as float64, so this handles the conversion.

func GetString

func GetString(m map[string]any, key string) string

GetString safely extracts a string value from a map and removes it. Returns empty string if the key doesn't exist or value is not a string.

func GetStringMap

func GetStringMap(m map[string]any, key string) map[string]string

GetStringMap safely extracts a map[string]string value from a map and removes it. Returns nil if the key doesn't exist or value is not a string map.

func GetStringSlice

func GetStringSlice(m map[string]any, key string) []string

GetStringSlice safely extracts a []string value from a map and removes it. Returns nil if the key doesn't exist or value is not a string array.

func MarshalWithExtras

func MarshalWithExtras(base map[string]any, extras map[string]any) ([]byte, error)

MarshalWithExtras marshals a base map while merging in extension fields. This is used in custom MarshalJSON implementations to combine known fields with unknown extension fields (typically x-* properties).

Example:

func (s *Schema) MarshalJSON() ([]byte, error) {
    base := map[string]any{
        "type": s.Type,
        "format": s.Format,
    }
    return jsonhelpers.MarshalWithExtras(base, s.Extra)
}

func SetIfMapNotEmpty

func SetIfMapNotEmpty[K comparable, V any](m map[string]any, key string, value map[K]V)

SetIfMapNotEmpty sets a map field in the map only if the map has length > 0. This is useful for MarshalJSON to avoid adding empty map fields. Note: In Go, both nil maps and empty maps should be omitted from JSON output.

func SetIfNotEmpty

func SetIfNotEmpty(m map[string]any, key string, value string)

SetIfNotEmpty sets a field in the map only if the value is not empty. This is useful for MarshalJSON to avoid adding empty fields to JSON output.

func SetIfNotNil

func SetIfNotNil(m map[string]any, key string, value any)

SetIfNotNil sets a field in the map only if the value is not nil. This is useful for MarshalJSON to avoid adding nil fields to JSON output.

func SetIfNotZero

func SetIfNotZero(m map[string]any, key string, value int)

SetIfNotZero sets a field in the map only if the value is not zero. This is useful for MarshalJSON to avoid adding zero-value numeric fields.

func SetIfSliceNotEmpty

func SetIfSliceNotEmpty[T any](m map[string]any, key string, value []T)

SetIfSliceNotEmpty sets a slice field in the map only if the slice has length > 0. This is useful for MarshalJSON to avoid adding empty slice fields. Note: In Go, both nil slices and empty slices should be omitted from JSON output.

func SetIfTrue

func SetIfTrue(m map[string]any, key string, value bool)

SetIfTrue sets a boolean field in the map only if the value is true. This is useful for MarshalJSON to avoid adding false boolean fields.

func SetOAS2PrimitiveFields added in v1.35.0

func SetOAS2PrimitiveFields(m map[string]any, f OAS2PrimitiveFields)

SetOAS2PrimitiveFields adds OAS 2.0 primitive type fields to a map. This is used by Parameter, Items, and Header MarshalJSON to reduce duplication. Note: For Items, Type should be set separately as a required field.

func SetSchemaConstraints added in v1.35.0

func SetSchemaConstraints(m map[string]any, c SchemaConstraints)

SetSchemaConstraints adds JSON Schema validation constraint fields to a map. This is used by Parameter, Items, and Header MarshalJSON to reduce duplication.

func UnmarshalExtras

func UnmarshalExtras(data map[string]any, knownFields map[string]bool) map[string]any

UnmarshalExtras extracts extension fields from a JSON object after known fields have been removed. This is used in custom UnmarshalJSON implementations.

The knownFields map should contain all known field names as keys. Any fields not in this map will be returned as extension fields.

Example:

func (s *Schema) UnmarshalJSON(data []byte) error {
    var temp map[string]any
    if err := json.Unmarshal(data, &temp); err != nil {
        return err
    }

    knownFields := map[string]bool{
        "type": true,
        "format": true,
    }

    // Extract known fields...
    s.Type = GetString(temp, "type")
    s.Format = GetString(temp, "format")

    // Store remaining as extras
    s.Extra = UnmarshalExtras(temp, knownFields)
    return nil
}

Types

type OAS2PrimitiveFields added in v1.35.0

type OAS2PrimitiveFields struct {
	Type             string
	Format           string
	Items            any
	CollectionFormat string
	Default          any
}

OAS2PrimitiveFields holds OAS 2.0 primitive type fields shared across Parameter, Items, and Header types in Swagger 2.0 specifications.

type SchemaConstraints added in v1.35.0

type SchemaConstraints struct {
	Maximum          *float64
	ExclusiveMaximum bool
	Minimum          *float64
	ExclusiveMinimum bool
	MaxLength        *int
	MinLength        *int
	Pattern          string
	MaxItems         *int
	MinItems         *int
	UniqueItems      bool
	Enum             []any
	MultipleOf       *float64
}

SchemaConstraints holds JSON Schema validation constraint fields. This is used for shared marshaling of constraint fields across Parameter, Items, and Header types.

Jump to

Keyboard shortcuts

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