maputil

package
v1.13.0 Latest Latest
Warning

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

Go to latest
Published: May 16, 2025 License: MIT Imports: 20 Imported by: 62

Documentation

Overview

Utilities for converting, manipulating, and iterating over maps

Index

Examples

Constants

This section is empty.

Variables

View Source
var MapXmlRootTagName = `data`
View Source
var MapXmlStructTagName = `xml`
View Source
var SkipDescendants = errors.New("skip descendants")
View Source
var UnmarshalStructTag string = `maputil`

Functions

func Append

func Append(maps ...map[string]any) map[string]any

func Apply

func Apply(input any, fn ApplyFunc) map[string]any

Recursively walk the given map, calling the ApplyFunc for each leaf value. If the second return value from the function is true, that value in the struct will be replaced with the first return value. If false, the value will be left as-is.

func ApplyStruct added in v1.6.4

func ApplyStruct(input any, fn ApplyFunc) map[string]any

The same as Apply(), but will descend into structs.

func Autotype

func Autotype(input any) map[string]any

Recursively walk the given map, performing automatic type conversion on all leaf nodes.

func CoalesceMap

func CoalesceMap(data map[string]any, fieldJoiner string) (map[string]any, error)

Take a deeply-nested map and return a flat (non-nested) map with keys whose intermediate tiers are joined with fieldJoiner

func CoalesceMapTyped

func CoalesceMapTyped(data map[string]any, fieldJoiner string, typePrefixSeparator string) (map[string]any, []error)

Take a deeply-nested map and return a flat (non-nested) map with keys whose intermediate tiers are joined with fieldJoiner Additionally, values will be converted to strings and keys will be prefixed with the datatype of the value

func Compact

func Compact(input map[string]any) (map[string]any, error)

Recursively remove all zero and empty values from the given map.

func DeepCopy

func DeepCopy(input any) map[string]any

Perform a deep copy of the given map.

func DeepCopyStruct added in v1.6.3

func DeepCopyStruct(input any) map[string]any

Perform a deep copy of the given map or struct, returning a map.

func DeepGet

func DeepGet(data any, path []string, fallbacks ...any) any

func DeepGetBool

func DeepGetBool(data any, path []string) bool

func DeepGetString

func DeepGetString(data any, path []string) string

func DeepJoin

func DeepJoin(input any, innerJoiner string, outerJoiner string, nestedSeparator string) string

Join the given map, using innerJoiner to join keys and values, and outerJoiner to join the resulting key-value lines.

func DeepSet

func DeepSet(data any, path []string, value any) any

func Delete added in v1.8.11

func Delete(data any, key any) error

Delete a key to a given value in the given map.

func DiffuseMap

func DiffuseMap(data map[string]any, fieldJoiner string) (map[string]any, error)

Take a flat (non-nested) map keyed with fields joined on fieldJoiner and return a deeply-nested map

func DiffuseMapTyped

func DiffuseMapTyped(data map[string]any, fieldJoiner string, typePrefixSeparator string) (map[string]any, []error)

Take a flat (non-nested) map keyed with fields joined on fieldJoiner and return a deeply-nested map

func Fprintf added in v1.8.41

func Fprintf(w io.Writer, format string, data ...any)

Same as Sprintf, but writes output to the given writer.

func Get

func Get(data any, key string, fallback ...any) any

func JSONPath added in v1.9.3

func JSONPath(data any, query string) (any, error)

Performs a JSONPath query against the given object and returns the results. JSONPath description, syntax, and examples are available at http://goessner.net/articles/JsonPath/.

func Join

func Join(input any, innerJoiner string, outerJoiner string) string

Join the given map, using innerJoiner to join keys and values, and outerJoiner to join the resulting key-value lines.

func Keys

func Keys(input any) []any

Return an interface slice of the keys of the given map.

func MapValues

func MapValues(input any) []any

Return the values from the given map.

func Merge

func Merge(first any, second any, options ...MergeOption) (map[string]any, error)

Recursively merge the contents of the second map into the first one and return the result.

func Pluck

func Pluck(sliceOfMaps any, key []string) []any

func Printf added in v1.8.41

func Printf(format string, data ...any)

Same as Sprintf, but prints its output to standard output.

Example (DeeplyNestedKeys)
Printf("Hello ${details.0.value|guest}! Your IP is: ${details.1.value|(unknown)}", map[string]any{
	`details`: []map[string]any{
		{
			`key`:   `username`,
			`value`: `friend`,
		}, {
			`key`:   `ipaddress`,
			`value`: `127.0.0.1`,
		},
	},
})
Output:

Hello friend! Your IP is: 127.0.0.1
Example (SuppliedWithData)
Printf("Hello ${username|guest}! Your IP is: ${ipaddress|(unknown)}", map[string]any{
	`username`:  `friend`,
	`ipaddress`: `127.0.0.1`,
})
Output:

Hello friend! Your IP is: 127.0.0.1
Example (UsingDefaultValues)
Printf("Hello ${username|guest}! Your IP is: ${ipaddress|(unknown)}")
Output:

Hello guest! Your IP is: (unknown)

func Set added in v1.5.53

func Set(data any, key any, value any) error

Set a key to a given value in the given map, reflect.Map Value, or slice/array.

func Split

func Split(input string, innerJoiner string, outerJoiner string) map[string]any

Split the given string, first on outerJoiner to form key-value lines, then each line on innerJoiner. Populates a map and returns the result.

func Sprintf added in v1.8.41

func Sprintf(format string, data ...any) string

Format the given string in the same manner as fmt.Sprintf, except data items that are maps or Map objects will be expanded using special patterns in the format string. Deeply-nested map values can be referenced using a format string "${path.to.value}". Missing keys will return an empty string, or a fallback value may be provided like so: "${path.to.value|fallback}". The value may also specify a standard fmt.Sprintf pattern with "${path.to.value:%02d}" (or "${path.to.value|fallback:%02d}" for fallback values.) Finally, a special case for time.Time values allows for the format string to be passed to time.Format: "${path.to.time:%January 2, 2006 (3:04pm)}".

func StringKeys

func StringKeys(input any) []string

Return a slice of strings representing the keys of the given map.

func Stringify

func Stringify(input map[string]any) map[string]string

Take the input map and convert all values to strings.

func StructFromMap

func StructFromMap(input map[string]any, populate any) error

Same as TaggedStructFromMapFunc, but no value conversion and uses the "maputil" struct tag.

func TaggedStructFromMap

func TaggedStructFromMap(input any, populate any, tagname string) error

Same as TaggedStructFromMapFunc, but does not perform any value conversion.

func TaggedStructFromMapFunc

func TaggedStructFromMapFunc(input any, populate any, tagname string, converter ConversionFunc) error

Take an input map, and populate the struct instance pointed to by "populate". Use the values of the tagname tag to inform which map keys should be used to fill struct fields, and if a Conversion function is given, that function will be used to allow values to be converted in preparation for becoming struct field values.

func Walk

func Walk(input any, walkFn WalkFunc) error

Recursively walk through the given map, calling walkFn for each intermediate and leaf value.

func WalkStruct added in v1.6.3

func WalkStruct(input any, walkFn WalkFunc) error

Recursively walk through the given map, calling walkFn for each intermediate and leaf value. This form behaves identically to Walk(), except that it will also recurse into structs, calling walkFn for all intermediate structs and fields.

Types

type ApplyFunc

type ApplyFunc func(key []string, value any) (any, bool)

type ConversionFunc

type ConversionFunc func(from reflect.Type, to reflect.Type, data any) (any, error)

type Item added in v1.8.33

type Item struct {
	Key   any
	Value any
	K     string
	V     typeutil.Variant
	// contains filtered or unexported fields
}

func (*Item) Set added in v1.8.47

func (self *Item) Set(value any) error

type ItemFunc added in v1.8.1

type ItemFunc func(key string, value typeutil.Variant) error

type IterOptions added in v1.8.34

type IterOptions struct {
	TagName  string
	SortKeys bool
}

type KeyTransformFunc added in v1.8.26

type KeyTransformFunc func(string) string

type Map

type Map struct {
	// contains filtered or unexported fields
}

A Map object (or "M" object) is a utility struct that makes it straightforward to work with interface data types that contain map-like data (has a reflect.Kind equal to reflect.Map).

func M

func M(data any) *Map

Create a new Variant map object from the given value. A wide range of values are accepted, and the best effort is made to convert those values into a usable map. Accepted values include typeutil.Variant, any value with a reflect.Kind of reflect.Map, sync.Map, another maputil.Map, url.Values, http.Header, or a string or []byte which will be decoded using json.Unmarshal if and only if the string begins with "{" and ends with "}".

func NewMap added in v1.9.1

func NewMap() *Map

func SliceOfMaps added in v1.12.2

func SliceOfMaps(input any) (maps []*Map)

Convert the given value to a slice using typeutil.Slice, then return each element as a Map.

func (*Map) Auto

func (self *Map) Auto(key string, fallbacks ...any) any

Return the value at key as an automatically converted value.

func (*Map) Bool

func (self *Map) Bool(key string) bool

Return the value at key as a bool.

func (*Map) Bytes

func (self *Map) Bytes(key string) []byte

Return the value at key as a byte slice.

func (*Map) Compact added in v1.10.5

func (self *Map) Compact() *Map

Reject all nil values from the map.

func (*Map) Delete added in v1.8.79

func (self *Map) Delete(key string)

Delete a value from the map.

func (*Map) Duration

func (self *Map) Duration(key string, fallbacks ...any) time.Duration

Return the value at key interpreted as a Duration.

func (*Map) Each added in v1.8.1

func (self *Map) Each(fn ItemFunc, tagName ...string) error

Iterate through each item in the map.

func (*Map) Err added in v1.7.35

func (self *Map) Err(key string) error

Return the value at key as an error, or nil if the value is not an error.

func (*Map) Float

func (self *Map) Float(key string, fallbacks ...any) float64

Return the value at key as a float.

func (*Map) Fprintf added in v1.8.41

func (self *Map) Fprintf(w io.Writer, format string)

Uses the extended Fprintf in this package, passing this map as the data used in the given format string.

func (*Map) Get

func (self *Map) Get(key string, fallbacks ...any) typeutil.Variant

Retrieve a value from the Map by the given dot.separated key, or return a fallback value. Return values are a typeutil.Variant, which can be easily coerced into various types.

func (*Map) Int

func (self *Map) Int(key string, fallbacks ...any) int64

Return the value at key as an integer.

func (*Map) IsZero added in v1.7.14

func (self *Map) IsZero(key string) bool

Return whether the value at the given key is that type's zero value.

func (*Map) Iter added in v1.8.33

func (self *Map) Iter(opts ...IterOptions) <-chan Item

func (*Map) JSON added in v1.8.80

func (self *Map) JSON(indent ...string) (data []byte)

func (*Map) JSONPath added in v1.9.3

func (self *Map) JSONPath(query string, fallback ...any) any

Performs a JSONPath query against the given object and returns the results. See JSONPath for details.

func (*Map) Keys added in v1.8.1

func (self *Map) Keys(tagName ...string) []any

Return the keys in this Map object. You may specify the name of a struct tag on the underlying object to use for generating key names.

func (*Map) Len added in v1.8.1

func (self *Map) Len() int

Return the length of the Map.

func (*Map) Map

func (self *Map) Map(key string, tagName ...string) map[typeutil.Variant]typeutil.Variant

Return the value at key as a Map. If the resulting value is nil or not a map type, a null Map will be returned. All values retrieved from a null Map will return that type's zero value.

func (*Map) MapNative added in v1.6.0

func (self *Map) MapNative(tagName ...string) map[string]any

Return the value as a map[string]any.

func (*Map) MapString added in v1.10.5

func (self *Map) MapString(tagName ...string) map[string]string

Return the value as a map[string]string.

func (*Map) MarshalJSON

func (self *Map) MarshalJSON() ([]byte, error)

func (*Map) MarshalXML added in v1.8.21

func (self *Map) MarshalXML(e *xml.Encoder, start xml.StartElement) error

Marshals the current data into XML. Nested maps are output as nested elements. Map values that are scalars (strings, numbers, bools, dates/times) will appear as attributes on the parent element.

func (*Map) Merge added in v1.10.5

func (self *Map) Merge(other any) int

Copy the items from a map into this one.

func (*Map) NInt added in v1.8.91

func (self *Map) NInt(key string, fallbacks ...any) int

Return the value at key as a native integer.

func (*Map) Set

func (self *Map) Set(key string, value any) typeutil.Variant

Set a value in the Map at the given dot.separated key to a value.

func (*Map) SetFunc added in v1.8.90

func (self *Map) SetFunc(key string, vfunc MapSetFunc) typeutil.Variant

Set a value in the Map using a function. The map will be locked to other modifications for the duration of the function's execution.

func (*Map) SetIfZero added in v1.7.14

func (self *Map) SetIfZero(key string, value any) (typeutil.Variant, bool)

Set a value in the Map at the given dot.separated key to a value, but only if the current value at that key is that type's zero value.

func (*Map) SetMarshalXmlGeneric added in v1.8.21

func (self *Map) SetMarshalXmlGeneric(yes bool)

func (*Map) SetMarshalXmlKeyFunc added in v1.8.26

func (self *Map) SetMarshalXmlKeyFunc(fn KeyTransformFunc)

Set a function that will be used to generate XML tag names when calling MarshalXML. This works for all keys, including ones that appear inside of maps.

func (*Map) SetRootTagName added in v1.8.21

func (self *Map) SetRootTagName(root string)

set the name of the root XML tag, used by MarshalXML.

func (*Map) SetValueIfNonZero added in v1.7.15

func (self *Map) SetValueIfNonZero(key string, value any) (typeutil.Variant, bool)

Set a value in the Map at the given dot.separated key to a value, but only if the new value is not a zero value.

func (*Map) Slice

func (self *Map) Slice(key string) []typeutil.Variant

Return the value at key as a slice. Scalar values will be returned as a slice containing only that value.

func (*Map) SliceOfMaps added in v1.13.0

func (self *Map) SliceOfMaps(key string) []*Map

Convert the given value to a slice using typeutil.Slice, then return each element as a Map.

func (*Map) Sprintf added in v1.8.41

func (self *Map) Sprintf(format string) string

Uses the extended Sprintf in this package, passing this map as the data used in the given format string.

func (*Map) String

func (self *Map) String(key string, fallbacks ...any) string

Return the value at key as a string.

func (*Map) StringKeys added in v1.8.1

func (self *Map) StringKeys(tagName ...string) []string

A string slice version of Keys()

func (*Map) Strings added in v1.6.7

func (self *Map) Strings(key string) []string

Same as Slice(), but returns a []string

func (*Map) Tag added in v1.8.2

func (self *Map) Tag(key string) *Map

Specify which struct tag to honor for generating field names when then underlying data is a struct.

func (*Map) Time

func (self *Map) Time(key string, fallbacks ...any) time.Time

Return the value at key interpreted as a Time.

func (*Map) UnmarshalJSON added in v1.8.44

func (self *Map) UnmarshalJSON(data []byte) error

func (*Map) Value

func (self *Map) Value() any

Return the underlying value the M-object was created with.

func (*Map) Walk added in v1.8.1

func (self *Map) Walk(fn WalkFunc) error

A recursive walk form of Each()

type MapSetFunc added in v1.8.90

type MapSetFunc func(m *Map, key string) any

type MergeOption added in v1.6.31

type MergeOption int
const (
	AppendValues MergeOption = iota
)

type MergeOptions added in v1.6.31

type MergeOptions []MergeOption

func (MergeOptions) Has added in v1.6.31

func (self MergeOptions) Has(option MergeOption) bool

type WalkFunc

type WalkFunc func(value any, path []string, isLeaf bool) error

Jump to

Keyboard shortcuts

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