ldvalue

package
v3.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2024 License: Apache-2.0 Imports: 9 Imported by: 48

Documentation

Overview

Package ldvalue provides the LaunchDarkly SDK's general value type, Value. LaunchDarkly supports the standard JSON data types of null, boolean, number, string, array, and object (map), for any feature flag variation or context attribute. The Value type can contain any of these.

This package also provides several helper types:

All value types in this package support several kinds of marshaling/unmarshaling, as follows:

JSON conversion with MarshalJSON and UnmarshalJSON

All value types in this package have MarshalJSON() and UnmarshalJSON() methods, so they can be used with the Marshal and Unmarshal functions in the encoding/json package. The result of JSON conversions depends on the type; see MarshalJSON() and UnmarshalJSON() for each type.

They also have a convenience method, JSONString(), that is equivalent to calling encoding/json.Marshal() and then casting to a string.

String conversion with String method

All value types in this package have a String() method, conforming to the fmt.Stringer interface. This is a human-readable string representation whose format depends on the type; see String() for each type.

Text conversion with TextMarshaler and TextUnmarshaler methods

All value types in this package have MarshalText() and UnmarshalText() methods allowing them to be used with any packages that support the encoding.TextMarshaler and encoding.TextUnmarshaler interfaces, such as gcfg. The format of this representation depends on the type, see MarshalText() and UnmarshalText() for each type.

JSON conversion with EasyJSON

The third-party library EasyJSON (https://github.com/mailru/easyjson) provides code generation of fast JSON converters, without using reflection at runtime. Because EasyJSON is not compatible with all runtime environments (due to the use of the "unsafe" package), LaunchDarkly code does not reference it by default; to enable the MarshalEasyJSON() and UnmarshalEasyJSON() methods for these types, you must set the build tag "launchdarkly_easyjson".

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ArrayBuilder

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

ArrayBuilder is a builder created by ArrayBuild, for creating immutable JSON arrays.

An ArrayBuilder should not be accessed by multiple goroutines at once.

Other ways to create a JSON array include:

  • Specifying all of its elements at once with ArrayOf.
  • Copying it from a Go slice with CopyArbitraryValue.
  • Creating it from the JSON serialization of an arbitrary type with FromJSONMarshal.
  • Parsing it from JSON data with Parse.

func ArrayBuild

func ArrayBuild() *ArrayBuilder

ArrayBuild creates a builder for constructing an immutable array Value.

arrayValue := ldvalue.ArrayBuild().Add(ldvalue.Int(100)).Add(ldvalue.Int(200)).Build()

func ArrayBuildWithCapacity

func ArrayBuildWithCapacity(capacity int) *ArrayBuilder

ArrayBuildWithCapacity creates a builder for constructing an immutable array Value. This is the same as ArrayBuild, but preallocates capacity for the underlying slice.

arrayValue := ldvalue.ArrayBuildWithCapacity(2).Add(ldvalue.Int(100)).Add(ldvalue.Int(200)).Build()

func (*ArrayBuilder) Add

func (b *ArrayBuilder) Add(value Value) *ArrayBuilder

Add appends an element to the array builder.

func (*ArrayBuilder) Build

func (b *ArrayBuilder) Build() Value

Build creates a Value containing the previously added array elements. Continuing to modify the same builder by calling ArrayBuilder.Add after that point does not affect the returned array.

type JSONStringer

type JSONStringer interface {
	// JSONString returns the JSON representation of the value as a string. This is
	// guaranteed to be logically equivalent to calling json.Marshal() and converting
	// the first return value to a string.
	//
	// Since types that support this method are by definition always convertible to JSON,
	// it does not need to return an error value so it can be easily used within an
	// expression.
	JSONString() string
}

JSONStringer is a common interface defining the JSONString() method, a convenience for marshaling a value to JSON and getting the result as a string.

type ObjectBuilder

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

ObjectBuilder is a builder created by ObjectBuild, for creating immutable JSON objects.

An ObjectBuilder should not be accessed by multiple goroutines at once.

Other ways to create a JSON object include:

func ObjectBuild

func ObjectBuild() *ObjectBuilder

ObjectBuild creates a builder for constructing an immutable JSON object Value.

objValue := ldvalue.ObjectBuild().Set("a", ldvalue.Int(100)).Set("b", ldvalue.Int(200)).Build()

func ObjectBuildWithCapacity

func ObjectBuildWithCapacity(capacity int) *ObjectBuilder

ObjectBuildWithCapacity creates a builder for constructing an immutable JSON object Value. This is the same as ObjectBuild, but preallocates capacity for the underlying map.

objValue := ldvalue.ObjectBuildWithCapacity(2).Set("a", ldvalue.Int(100)).Set("b", ldvalue.Int(200)).Build()

func (*ObjectBuilder) Build

func (b *ObjectBuilder) Build() Value

Build creates a Value containing the previously specified key-value pairs. Continuing to modify the same builder by calling ObjectBuilder.Set after that point does not affect the returned object.

func (*ObjectBuilder) Remove

func (b *ObjectBuilder) Remove(key string) *ObjectBuilder

Remove removes a key from the builder if it exists.

func (*ObjectBuilder) Set

func (b *ObjectBuilder) Set(key string, value Value) *ObjectBuilder

Set sets a key-value pair in the object builder to a value of any JSON type.

func (*ObjectBuilder) SetBool

func (b *ObjectBuilder) SetBool(key string, value bool) *ObjectBuilder

SetBool sets a key-value pair in the object builder to a boolean value.

This is exactly equivalent to b.Set(key, ldvalue.Bool(value)).

func (*ObjectBuilder) SetFloat64

func (b *ObjectBuilder) SetFloat64(key string, value float64) *ObjectBuilder

SetFloat64 sets a key-value pair in the object builder to a float64 numeric value.

This is exactly equivalent to b.Set(key, ldvalue.Float64(value)).

func (*ObjectBuilder) SetInt

func (b *ObjectBuilder) SetInt(key string, value int) *ObjectBuilder

SetInt sets a key-value pair in the object builder to an integer numeric value.

This is exactly equivalent to b.Set(key, ldvalue.Int(value)).

func (*ObjectBuilder) SetString

func (b *ObjectBuilder) SetString(key string, value string) *ObjectBuilder

SetString sets a key-value pair in the object builder to a string value.

This is exactly equivalent to b.Set(key, ldvalue.String(value)).

type OptionalBool

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

OptionalBool represents a bool that may or may not have a value. This is similar to using a bool pointer to distinguish between a false value and nil, but it is safer because it does not expose a pointer to any mutable value.

To create an instance with a bool value, use NewOptionalBool. There is no corresponding method for creating an instance with no value; simply use the empty literal OptionalBool{}.

ob1 := NewOptionalBool(1)
ob2 := NewOptionalBool(false) // this has a value which is false
ob3 := OptionalBool{}         // this does not have a value

This can also be used as a convenient way to construct a bool pointer within an expression. For instance, this example causes myIntPointer to point to the bool value true:

var myBoolPointer *int = NewOptionalBool(true).AsPointer()

The reason LaunchDarkly code uses this specific type instead of a generic Optional[T] is for efficiency in JSON marshaling/unmarshaling. A generic type would have to use reflection and dynamic typecasting for its marshal/unmarshal methods.

func NewOptionalBool

func NewOptionalBool(value bool) OptionalBool

NewOptionalBool constructs an OptionalBool that has a bool value.

There is no corresponding method for creating an OptionalBool with no value; simply use the empty literal OptionalBool{}.

func NewOptionalBoolFromPointer

func NewOptionalBoolFromPointer(valuePointer *bool) OptionalBool

NewOptionalBoolFromPointer constructs an OptionalBool from a bool pointer. If the pointer is non-nil, then the OptionalBool copies its value; otherwise the OptionalBool has no value.

func (OptionalBool) AsPointer

func (o OptionalBool) AsPointer() *bool

AsPointer returns the OptionalBool's value as a bool pointer if it has a value, or nil otherwise.

The bool value, if any, is copied rather than returning to a pointer to the internal field.

func (OptionalBool) AsValue

func (o OptionalBool) AsValue() Value

AsValue converts the OptionalBool to a Value, which is either Null() or a boolean value.

func (OptionalBool) BoolValue

func (o OptionalBool) BoolValue() bool

BoolValue returns the OptionalBool's value, or false if it has no value.

func (OptionalBool) Get

func (o OptionalBool) Get() (bool, bool)

Get is a combination of BoolValue and IsDefined. If the OptionalBool contains a bool value, it returns that value and true; otherwise it returns false and false.

func (OptionalBool) IsDefined

func (o OptionalBool) IsDefined() bool

IsDefined returns true if the OptionalBool contains a bool value, or false if it has no value.

func (OptionalBool) JSONString

func (o OptionalBool) JSONString() string

JSONString returns the JSON representation of the value as a string. This is guaranteed to be logically equivalent to calling json.Marshal and converting the first return value to a string.

Since types that support this method are by definition always convertible to JSON, it does not need to return an error value so it can be easily used within an expression.

func (OptionalBool) MarshalJSON

func (o OptionalBool) MarshalJSON() ([]byte, error)

MarshalJSON converts the OptionalBool to its JSON representation.

The output will be either a JSON boolean or null. Note that the "omitempty" tag for a struct field will not cause an empty OptionalBool field to be omitted; it will be output as null. If you want to completely omit a JSON property when there is no value, it must be a bool pointer instead of an OptionalBool; use OptionalBool.AsPointer to get a pointer.

func (OptionalBool) MarshalText

func (o OptionalBool) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

This may be useful with packages that support describing arbitrary types via that interface.

The behavior for OptionalBool is that a true or false value produces the string "true" or "false", and an undefined value produces an empty string.

func (OptionalBool) OrElse

func (o OptionalBool) OrElse(valueIfEmpty bool) bool

OrElse returns the OptionalBool's value if it has one, or else the specified fallback value.

func (*OptionalBool) ReadFromJSONReader

func (o *OptionalBool) ReadFromJSONReader(r *jreader.Reader)

ReadFromJSONReader provides JSON deserialization for use with the jsonstream API.

This implementation is used by the SDK in cases where it is more efficient than json.Unmarshal. See github.com/launchdarkly/go-jsonstream/v3 for more details.

func (OptionalBool) String

func (o OptionalBool) String() string

String returns a human-readable string representation of the value.

Currently, this is defined as being either "true", "false, or "[none]" if it has no value. However, the specific representation format is subject to change and should not be relied on in code; it is intended for convenience in logging or debugging.

func (*OptionalBool) UnmarshalJSON

func (o *OptionalBool) UnmarshalJSON(data []byte) error

UnmarshalJSON parses an OptionalBool from JSON.

The input must be either a JSON boolean or null.

func (*OptionalBool) UnmarshalText

func (o *OptionalBool) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

This may be useful with packages that support parsing arbitrary types via that interface, such as gcfg.

If the input data is nil or empty, the result is an empty OptionalBool{}. Otherwise, it recognizes "true" or "false" as valid inputs and returns an error for all other values.

This allows OptionalBool to be used with packages that can parse text content, such as gcfg.

func (OptionalBool) WriteToJSONWriter

func (o OptionalBool) WriteToJSONWriter(w *jwriter.Writer)

WriteToJSONWriter provides JSON serialization for use with the jsonstream API.

This implementation is used by the SDK in cases where it is more efficient than json.Marshal. See github.com/launchdarkly/go-jsonstream/v3 for more details.

type OptionalInt

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

OptionalInt represents an int that may or may not have a value. This is similar to using an int pointer to distinguish between a zero value and nil, but it is safer because it does not expose a pointer to any mutable value.

To create an instance with an int value, use NewOptionalInt. There is no corresponding method for creating an instance with no value; simply use the empty literal OptionalInt{}.

oi1 := NewOptionalInt(1)
oi2 := NewOptionalInt(0) // this has a value which is zero
oi3 := OptionalInt{}     // this does not have a value

This can also be used as a convenient way to construct an int pointer within an expression. For instance, this example causes myIntPointer to point to the int value 2:

var myIntPointer *int = NewOptionalInt("x").AsPointer()

This type is used in ldreason.EvaluationDetail.VariationIndex, and for other similar fields in the LaunchDarkly Go SDK where an int value may or may not be defined.

The reason LaunchDarkly code uses this specific type instead of a generic Optional[T] is for efficiency in JSON marshaling/unmarshaling. A generic type would have to use reflection and dynamic typecasting for its marshal/unmarshal methods.

func NewOptionalInt

func NewOptionalInt(value int) OptionalInt

NewOptionalInt constructs an OptionalInt that has an int value.

There is no corresponding method for creating an OptionalInt with no value; simply use the empty literal OptionalInt{}.

func NewOptionalIntFromPointer

func NewOptionalIntFromPointer(valuePointer *int) OptionalInt

NewOptionalIntFromPointer constructs an OptionalInt from an int pointer. If the pointer is non-nil, then the OptionalInt copies its value; otherwise the OptionalInt has no value.

func (OptionalInt) AsPointer

func (o OptionalInt) AsPointer() *int

AsPointer returns the OptionalInt's value as an int pointer if it has a value, or nil otherwise.

The int value, if any, is copied rather than returning to a pointer to the internal field.

func (OptionalInt) AsValue

func (o OptionalInt) AsValue() Value

AsValue converts the OptionalInt to a Value, which is either Null() or a number value.

func (OptionalInt) Get

func (o OptionalInt) Get() (int, bool)

Get is a combination of IntValue and IsDefined. If the OptionalInt contains an int value, it returns that value and true; otherwise it returns zero and false.

func (OptionalInt) IntValue

func (o OptionalInt) IntValue() int

IntValue returns the OptionalInt's value, or zero if it has no value.

func (OptionalInt) IsDefined

func (o OptionalInt) IsDefined() bool

IsDefined returns true if the OptionalInt contains an int value, or false if it has no value.

func (OptionalInt) JSONString

func (o OptionalInt) JSONString() string

JSONString returns the JSON representation of the value as a string. This is guaranteed to be logically equivalent to calling json.Marshal and converting the first return value to a string.

Since types that support this method are by definition always convertible to JSON, it does not need to return an error value so it can be easily used within an expression.

func (OptionalInt) MarshalJSON

func (o OptionalInt) MarshalJSON() ([]byte, error)

MarshalJSON converts the OptionalInt to its JSON representation.

The output will be either a JSON number or null. Note that the "omitempty" tag for a struct field will not cause an empty OptionalInt field to be omitted; it will be output as null. If you want to completely omit a JSON property when there is no value, it must be an int pointer instead of an OptionalInt; use OptionalInt.AsPointer method to get a pointer.

func (OptionalInt) MarshalText

func (o OptionalInt) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

This may be useful with packages that support describing arbitrary types via that interface.

The behavior for OptionalBool is that a true or false value produces a decimal numeric string, and an undefined value produces an empty string.

func (OptionalInt) OrElse

func (o OptionalInt) OrElse(valueIfEmpty int) int

OrElse returns the OptionalInt's value if it has one, or else the specified fallback value.

func (*OptionalInt) ReadFromJSONReader

func (o *OptionalInt) ReadFromJSONReader(r *jreader.Reader)

ReadFromJSONReader provides JSON deserialization for use with the jsonstream API.

This implementation is used by the SDK in cases where it is more efficient than json.Unmarshal. See github.com/launchdarkly/go-jsonstream/v3 for more details.

func (OptionalInt) String

func (o OptionalInt) String() string

String returns a human-readable string representation of the value.

Currently, this is defined as being either a numeric string or "[none]" if it has no value. However, the specific representation format is subject to change and should not be relied on in code; it is intended for convenience in logging or debugging.

func (*OptionalInt) UnmarshalJSON

func (o *OptionalInt) UnmarshalJSON(data []byte) error

UnmarshalJSON parses an OptionalInt from JSON.

The input must be either a JSON number that is an integer or null.

func (*OptionalInt) UnmarshalText

func (o *OptionalInt) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

This may be useful with packages that support parsing arbitrary types via that interface, such as gcfg.

If the input data is nil or empty, the result is an empty OptionalInt{}. Otherwise, it uses strconv.Atoi() to parse a numeric value.

This allows OptionalInt to be used with packages that can parse text content, such as gcfg.

func (OptionalInt) WriteToJSONWriter

func (o OptionalInt) WriteToJSONWriter(w *jwriter.Writer)

WriteToJSONWriter provides JSON serialization for use with the jsonstream API.

This implementation is used by the SDK in cases where it is more efficient than json.Marshal. See github.com/launchdarkly/go-jsonstream/v3 for more details.

type OptionalString

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

OptionalString represents a string that may or may not have a value. This is similar to using a string pointer to distinguish between an empty string and nil, but it is safer because it does not expose a pointer to any mutable value.

Unlike Value, which can contain a value of any JSON-compatible type, OptionalString either contains a string or nothing. To create an instance with a string value, use NewOptionalString. There is no corresponding method for creating an instance with no value; simply use the empty literal OptionalString{}.

os1 := NewOptionalString("this has a value")
os2 := NewOptionalString("") // this has a value which is an empty string
os2 := OptionalString{} // this does not have a value

This can also be used as a convenient way to construct a string pointer within an expression. For instance, this example causes myStringPointer to point to the string "x":

var myStringPointer *string = NewOptionalString("x").AsPointer()

The reason LaunchDarkly code uses this specific type instead of a generic Optional[T] is for efficiency in JSON marshaling/unmarshaling. A generic type would have to use reflection and dynamic typecasting for its marshal/unmarshal methods.

func NewOptionalString

func NewOptionalString(value string) OptionalString

NewOptionalString constructs an OptionalString that has a string value.

There is no corresponding method for creating an OptionalString with no value; simply use the empty literal OptionalString{}.

func NewOptionalStringFromPointer

func NewOptionalStringFromPointer(valuePointer *string) OptionalString

NewOptionalStringFromPointer constructs an OptionalString from a string pointer. If the pointer is non-nil, then the OptionalString copies its value; otherwise the OptionalString has no value.

func (OptionalString) AsPointer

func (o OptionalString) AsPointer() *string

AsPointer returns the OptionalString's value as a string pointer if it has a value, or nil otherwise.

The string value, if any, is copied rather than returning to a pointer to the internal field.

func (OptionalString) AsValue

func (o OptionalString) AsValue() Value

AsValue converts the OptionalString to a Value, which is either Null() or a string value.

func (OptionalString) Get

func (o OptionalString) Get() (string, bool)

Get is a combination of StringValue and IsDefined. If the OptionalString contains a string value, it returns that value and true; otherwise it returns an empty string and false.

func (OptionalString) IsDefined

func (o OptionalString) IsDefined() bool

IsDefined returns true if the OptionalString contains a string value, or false if it has no value.

func (OptionalString) JSONString

func (o OptionalString) JSONString() string

JSONString returns the JSON representation of the value as a string. This is guaranteed to be logically equivalent to calling json.Marshal and converting the first return value to a string.

Since types that support this method are by definition always convertible to JSON, it does not need to return an error value so it can be easily used within an expression.

func (OptionalString) MarshalJSON

func (o OptionalString) MarshalJSON() ([]byte, error)

MarshalJSON converts the OptionalString to its JSON representation.

The output will be either a JSON string or null. Note that the "omitempty" tag for a struct field will not cause an empty OptionalString field to be omitted; it will be output as null. If you want to completely omit a JSON property when there is no value, it must be a string pointer instead of an OptionalString; use OptionalString.AsPointer method to get a pointer.

func (OptionalString) MarshalText

func (o OptionalString) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

This may be useful with packages that support describing arbitrary types via that interface.

The behavior for OptionalString is that a defined string value produces the same string, and an undefined value produces nil.

func (OptionalString) OnlyIfNonEmptyString

func (o OptionalString) OnlyIfNonEmptyString() OptionalString

OnlyIfNonEmptyString returns the same OptionalString unless it contains an empty string (""), in which case it returns an OptionalString that has no value.

func (OptionalString) OrElse

func (o OptionalString) OrElse(valueIfEmpty string) string

OrElse returns the OptionalString's value if it has one, or else the specified fallback value.

func (*OptionalString) ReadFromJSONReader

func (o *OptionalString) ReadFromJSONReader(r *jreader.Reader)

ReadFromJSONReader provides JSON deserialization for use with the jsonstream API.

This implementation is used by the SDK in cases where it is more efficient than json.Unmarshal. See github.com/launchdarkly/go-jsonstream/v3 for more details.

func (OptionalString) String

func (o OptionalString) String() string

String returns a human-readable string representation of the value.

Currently, this is defined as being either the string value itself or "[none]" if it has no value. However, the specific representation format is subject to change and should not be relied on in code; it is intended for convenience in logging or debugging.

Since String() is used by methods like fmt.Printf, if you want to use the actual string value of the OptionalString instead of this special representation, you should call StringValue():

s := OptionalString{}
fmt.Printf("it is '%s'", s) // prints "it is '[none]'"
fmt.Printf("it is '%s'", s.StringValue()) // prints "it is ''"

func (OptionalString) StringValue

func (o OptionalString) StringValue() string

StringValue returns the OptionalString's value, or an empty string if it has no value.

func (*OptionalString) UnmarshalJSON

func (o *OptionalString) UnmarshalJSON(data []byte) error

UnmarshalJSON parses an OptionalString from JSON.

The input must be either a JSON string or null.

func (*OptionalString) UnmarshalText

func (o *OptionalString) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

This may be useful with packages that support parsing arbitrary types via that interface, such as gcfg.

If the byte slice is nil, rather than zero-length, it will set the target value to an empty OptionalString{}. Otherwise, it will set it to a string value.

func (OptionalString) WriteToJSONWriter

func (o OptionalString) WriteToJSONWriter(w *jwriter.Writer)

WriteToJSONWriter provides JSON serialization for use with the jsonstream API.

This implementation is used by the SDK in cases where it is more efficient than json.Marshal. See github.com/launchdarkly/go-jsonstream/v3 for more details.

type Value

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

Value represents any of the data types supported by JSON, all of which can be used for a LaunchDarkly feature flag variation, or for an attribute in an evaluation context. Value instances are immutable.

Uses of JSON types in LaunchDarkly

LaunchDarkly feature flags can have variations of any JSON type other than null. If you want to evaluate a feature flag in a general way that does not have expectations about the variation type, or if the variation value is a complex data structure such as an array or object, you can use the SDK method github.com/launchdarkly/go-server-sdk/v6/LDClient.JSONVariationDetail to get the value and then use Value methods to examine it.

Similarly, attributes of an evaluation context (github.com/launchdarkly/go-sdk-common/v3/ldcontext.Context) can have variations of any JSON type other than null. If you want to set a context attribute in a general way that will accept any type, or set the attribute value to a complex data structure such as an array or object, you can use the builder method github.com/launchdarkly/go-sdk-common/v3/ldcontext.Builder.SetValue.

Arrays and objects have special meanings in LaunchDarkly flag evaluation:

  • An array of values means "try to match any of these values to the targeting rule."
  • An object allows you to match a property within the object to the targeting rule. For instance, in the example above, a targeting rule could reference /objectAttr1/color to match the value "green". Nested property references like /objectAttr1/address/street are allowed if a property contains another JSON object.

Constructors and builders

The most efficient way to create a Value is with typed constructors such as Bool and String, or, for complex data, the builders ArrayBuild and ObjectBuild. However, any value that can be represented in JSON can be converted to a Value with CopyArbitraryValue or FromJSONMarshal, or you can parse a Value from JSON. The following code examples all produce the same value:

value := ldvalue.ObjectBuild().SetString("thing", "x").Build()

type MyStruct struct {
	Thing string `json:"thing"`
}
value := ldvalue.FromJSONMarshal(MyStruct{Thing: "x"})

value := ldvalue.Parse([]byte(`{"thing": "x"}`))

Comparisons

You cannot compare Value instances with the == operator, because the struct may contain a slice. or a map. Value has the Value.Equal method for this purpose; reflect.DeepEqual will also work.

func ArrayOf

func ArrayOf(items ...Value) Value

ArrayOf creates an array Value from a list of Values.

This requires a slice copy to ensure immutability; otherwise, an existing slice could be passed using the spread operator, and then modified. However, since Value is itself immutable, it does not need to deep-copy each item.

func Bool

func Bool(value bool) Value

Bool creates a boolean Value.

func CopyArbitraryValue

func CopyArbitraryValue(anyValue any) Value

CopyArbitraryValue creates a Value from an arbitrary value of any type.

If the value is nil, a boolean, an integer, a floating-point number, or a string, it becomes the corresponding JSON primitive value type. If it is a slice of values ([]any or []Value), it is deep-copied to an array value. If it is a map of strings to values (map[string]any or map[string]Value), it is deep-copied to an object value.

If it is a pointer to any of the above types, then it is dereferenced and treated the same as above, unless the pointer is nil, in which case it becomes Null().

For all other types, the value is marshaled to JSON and then converted to the corresponding Value type, just as if you had called FromJSONMarshal. The difference is only that CopyArbitraryValue is more efficient for primitive types, slices, and maps, which it can copy without first marshaling them to JSON.

func CopyObject

func CopyObject(m map[string]Value) Value

CopyObject creates a Value by copying an existing map[string]Value.

If you want to copy a map[string]interface{} instead, use CopyArbitraryValue.

func Float64

func Float64(value float64) Value

Float64 creates a numeric Value from a float64.

func FromJSONMarshal

func FromJSONMarshal(anyValue any) Value

FromJSONMarshal creates a Value from the JSON representation of any Go value.

This is based on encoding/json.Marshal, so it can be used with any value that can be passed to that function, and follows the usual behavior of json.Marshal with regard to types and field names. For instance, you could use it with a custom struct type:

type MyStruct struct {
	Thing string `json:"thing"`
}
value := ldvalue.FromJSONMarshal(MyStruct{Thing: "x"})

It is equivalent to calling json.Marshal followed by Parse, so it incurs the same overhead of first marshaling the value and then parsing the resulting JSON.

func Int

func Int(value int) Value

Int creates a numeric Value from an integer.

Note that all numbers are represented internally as the same type (float64), so Int(2) is exactly equal to Float64(2).

func Null

func Null() Value

Null creates a null Value.

func Parse

func Parse(jsonData []byte) Value

Parse returns a Value parsed from a JSON string, or Null if it cannot be parsed.

This is simply a shortcut for calling json.Unmarshal and disregarding errors. It is meant for use in test scenarios where malformed data is not a concern.

func Raw

func Raw(value json.RawMessage) Value

Raw creates an unparsed JSON Value.

This constructor stores a copy of the json.RawMessage value as-is without syntax validation, and sets the type of the Value to RawType. The advantage of this is that if you have some data that you do not expect to do any computations with, but simply want to include in JSON data to be sent to LaunchDarkly, the original data will be output as-is and does not need to be parsed.

However, if you do anything that involves inspecting the value (such as comparing it to another value, or evaluating a feature flag that references the value in a context attribute), the JSON data will be parsed automatically each time that happens, so there will be no efficiency gain. Therefore, if you expect any such operations to happen, it is better to use Parse instead to parse the JSON immediately, or use value builder methods such as ObjectBuild.

If you pass malformed data that is not valid JSON, you will get malformed data if it is re-encoded to JSON. It is the caller's responsibility to make sure the json.RawMessage really is valid JSON. However, since it is easy to mistakenly write json.RawMessage(nil) (an invalid zero-length value) when what is really meant is a JSON null value, this constructor transparently converts both json.RawMessage(nil) and json.RawMessage([]byte("")) to Null().

func String

func String(value string) Value

String creates a string Value.

func (Value) AsArbitraryValue

func (v Value) AsArbitraryValue() any

AsArbitraryValue returns the value in its simplest Go representation, typed as "any".

This is nil for a null value; for primitive types, it is bool, float64, or string (all numbers are represented as float64 because that is Go's default when parsing from JSON). For unparsed JSON data created with Raw, it returns a json.RawMessage.

Arrays and objects are represented as []any and map[string]any. They are deep-copied, which preserves immutability of the Value but may be an expensive operation. To examine array and object values without copying the whole data structure, use getter methods: Value.Count, Value.Keys, Value.GetByIndex, Value.TryGetByIndex, Value.GetByKey, Value.TryGetByKey.

func (Value) AsOptionalString

func (v Value) AsOptionalString() OptionalString

AsOptionalString converts the value to the OptionalString type, which contains either a string value or nothing if the original value was not a string.

func (Value) AsPointer

func (v Value) AsPointer() *Value

AsPointer returns either a pointer to a copy of this Value, or nil if it is a null value.

This may be desirable if you are serializing a struct that contains a Value, and you want that field to be completely omitted if the Value is null; since the "omitempty" tag only works for pointers, you can declare the field as a *Value like so:

type MyJsonStruct struct {
    AnOptionalField *Value `json:"anOptionalField,omitempty"`
}
s := MyJsonStruct{AnOptionalField: someValue.AsPointer()}

func (Value) AsRaw

func (v Value) AsRaw() json.RawMessage

AsRaw returns the value as a json.RawMessage.

If the value was originally created with Raw, it returns a copy of the original value. For all other values, it converts the value to its JSON representation and returns that representation.

Note that the Raw constructor does not do any syntax validation, so if you create a Value from a malformed string such as ldvalue.Raw(json.RawMessage("{{{")), you will get back the same string from AsRaw().

func (Value) AsValueArray

func (v Value) AsValueArray() ValueArray

AsValueArray converts the Value to the immutable ValueArray type if it is a JSON array. Otherwise it returns a ValueArray in an uninitialized (nil) state. This is an efficient operation that does not allocate a new slice.

If the value is a JSON array or object created from unparsed JSON with Raw, this method first parses the JSON, which can be inefficient.

func (Value) AsValueMap

func (v Value) AsValueMap() ValueMap

AsValueMap converts the Value to the immutable ValueMap type if it is a JSON object. Otherwise it returns a ValueMap in an uninitialized (nil) state. This is an efficient operation that does not allocate a new map.

If the value is a JSON array or object created from unparsed JSON with Raw, this method first parses the JSON, which can be inefficient.

func (Value) BoolValue

func (v Value) BoolValue() bool

BoolValue returns the Value as a boolean.

If the Value is not a boolean, it returns false.

func (Value) Count

func (v Value) Count() int

Count returns the number of elements in an array or JSON object.

For values of any other type, it returns zero.

If the value is a JSON array or object created from unparsed JSON with Raw, this method first parses the JSON, which can be inefficient.

func (Value) Equal

func (v Value) Equal(other Value) bool

Equal tests whether this Value is equal to another, in both type and value.

For arrays and objects, this is a deep equality test. This method behaves the same as reflect.DeepEqual, but is slightly more efficient.

Unparsed JSON values created with Raw will be parsed in order to do this comparison.

func (Value) Float64Value

func (v Value) Float64Value() float64

Float64Value returns the value as a float64.

If the Value is not numeric, it returns zero.

func (Value) GetByIndex

func (v Value) GetByIndex(index int) Value

GetByIndex gets an element of an array by index.

If the value is not an array, or if the index is out of range, it returns Null().

If the value is a JSON array or object created from unparsed JSON with Raw, this method first parses the JSON, which can be inefficient.

func (Value) GetByKey

func (v Value) GetByKey(name string) Value

GetByKey gets a value from a JSON object by key.

If the value is not an object, or if the key is not found, it returns Null().

If the value is a JSON array or object created from unparsed JSON with Raw, this method first parses the JSON, which can be inefficient.

func (Value) IntValue

func (v Value) IntValue() int

IntValue returns the value as an int.

If the Value is not numeric, it returns zero. If the value is a number but not an integer, it is rounded toward zero (truncated).

func (Value) IsBool

func (v Value) IsBool() bool

IsBool returns true if the Value is a boolean.

func (Value) IsDefined

func (v Value) IsDefined() bool

IsDefined returns true if the Value is anything other than null.

This is exactly equivalent to !v.IsNull(), but is provided as a separate method for consistency with other types that have an IsDefined() method.

func (Value) IsInt

func (v Value) IsInt() bool

IsInt returns true if the Value is an integer.

JSON does not have separate types for integer and floating-point values; they are both just numbers. IsInt returns true if and only if the actual numeric value has no fractional component, so Int(2).IsInt() and Float64(2.0).IsInt() are both true.

func (Value) IsNull

func (v Value) IsNull() bool

IsNull returns true if the Value is a null.

func (Value) IsNumber

func (v Value) IsNumber() bool

IsNumber returns true if the Value is numeric.

func (Value) IsString

func (v Value) IsString() bool

IsString returns true if the Value is a string.

func (Value) JSONString

func (v Value) JSONString() string

JSONString returns the JSON representation of the value.

This is equivalent to calling Value.MarshalJSON and converting the result to a string. Since all Values by definition can be represented in JSON, this method does not need to return an error value so it can be easily used within an expression.

func (Value) Keys

func (v Value) Keys(sliceIn []string) []string

Keys returns the keys of a JSON object as a slice.

If a non-nil slice is passed in, it will be reused to hold the return values if it has enough capacity. Otherwise, a new slice is allocated if there are any keys.

The ordering of the keys is undefined.

If the value is a JSON array or object created from unparsed JSON with Raw, this method first parses the JSON, which can be inefficient.

func (Value) MarshalJSON

func (v Value) MarshalJSON() ([]byte, error)

MarshalJSON converts the Value to its JSON representation.

Note that the "omitempty" tag for a struct field will not cause an empty Value field to be omitted; it will be output as null. If you want to completely omit a JSON property when there is no value, it must be a pointer; use AsPointer().

func (Value) MarshalText

func (v Value) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

This may be useful with packages that support describing arbitrary types via that interface.

The behavior for Value is the same as Value.MarshalJSON. For instance, ldvalue.Bool(true) becomes the string "true", and ldvalue.String("x") becomes the string "\"x\"".

func (*Value) ReadFromJSONReader

func (v *Value) ReadFromJSONReader(r *jreader.Reader)

ReadFromJSONReader provides JSON deserialization for use with the jsonstream API.

This implementation is used by the SDK in cases where it is more efficient than json.Unmarshal. See github.com/launchdarkly/go-jsonstream/v3 for more details.

func (Value) String

func (v Value) String() string

String converts the value to a string representation, equivalent to Value.JSONString.

This is different from Value.StringValue, which returns the actual string for a string value or an empty string for anything else. For instance, Int(2).StringValue() returns "2" and String("x").StringValue() returns "\"x\"", whereas Int(2).AsString() returns "" and String("x").AsString() returns "x".

This method is provided because it is common to use the fmt.Stringer interface as a quick way to summarize the contents of a value. The simplest way to do so in this case is to use the JSON representation.

func (Value) StringValue

func (v Value) StringValue() string

StringValue returns the value as a string.

If the value is not a string, it returns an empty string.

This is different from String, which returns a string representation of any value type, including any necessary JSON delimiters.

func (Value) Transform

func (v Value) Transform(fn func(index int, key string, value Value) (Value, bool)) Value

Transform applies a transformation function to a Value, returning a new Value.

The behavior is as follows:

If the input value is Null(), the return value is always Null() and the function is not called.

If the input value is an array, fn is called for each element, with the element's index in the first parameter, "" in the second, and the element value in the third. The return values of fn can be either a transformed value and true, or any value and false to remove the element.

ldvalue.ArrayOf(ldvalue.Int(1), ldvalue.Int(2), ldvalue.Int(3)).Build().
    Transform(func(index int, key string, value Value) (Value, bool) {
        if value.IntValue() == 2 {
            return ldvalue.Null(), false
        }
        return ldvalue.Int(value.IntValue() * 10), true
    })
// returns [10, 30]

If the input value is an object, fn is called for each key-value pair, with 0 in the first parameter, the key in the second, and the value in the third. Again, fn can choose to either transform or drop the value.

ldvalue.ObjectBuild().Set("a", ldvalue.Int(1)).Set("b", ldvalue.Int(2)).Set("c", ldvalue.Int(3)).Build().
    Transform(func(index int, key string, value Value) (Value, bool) {
        if key == "b" {
            return ldvalue.Null(), false
        }
        return ldvalue.Int(value.IntValue() * 10), true
    })
// returns {"a": 10, "c": 30}

For any other value type, fn is called once for that value; if it provides a transformed value and true, the transformed value is returned, otherwise Null().

ldvalue.Int(2).Transform(func(index int, key string, value Value) (Value, bool) {
    return ldvalue.Int(value.IntValue() * 10), true
})
// returns numeric value of 20

For array and object values, if the function does not modify or drop any values, the exact same instance is returned without allocating a new slice or map.

If the value is a JSON array or object created from unparsed JSON with Raw, this method first parses the JSON, which can be inefficient.

func (Value) TryGetByIndex

func (v Value) TryGetByIndex(index int) (Value, bool)

TryGetByIndex gets an element of an array by index, with a second return value of true if successful.

If the value is not an array, or if the index is out of range, it returns (Null(), false).

If the value is a JSON array or object created from unparsed JSON with Raw, this method first parses the JSON, which can be inefficient.

func (Value) TryGetByKey

func (v Value) TryGetByKey(name string) (Value, bool)

TryGetByKey gets a value from a JSON object by key, with a second return value of true if successful.

If the value is not an object, or if the key is not found, it returns (Null(), false).

If the value is a JSON array or object created from unparsed JSON with Raw, this method first parses the JSON, which can be inefficient.

func (Value) Type

func (v Value) Type() ValueType

Type returns the ValueType of the Value.

func (*Value) UnmarshalJSON

func (v *Value) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a Value from JSON.

func (*Value) UnmarshalText

func (v *Value) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

This may be useful with packages that support parsing arbitrary types via that interface, such as gcfg.

The behavior for Value is that if the input is a valid JSON representation-- such as the string "null", "false", "1", or "[1, 2]"-- it is parsed identically to json.Unmarshal(). Otherwise, it is assumed to be a string, and the result is the same as calling ldvalue.String() with the same value. This behavior is intended to be similar to the default behavior of YAML v2 parsers.

func (Value) WriteToJSONWriter

func (v Value) WriteToJSONWriter(w *jwriter.Writer)

WriteToJSONWriter provides JSON serialization for use with the jsonstream API.

This implementation is used by the SDK in cases where it is more efficient than json.Marshal. See github.com/launchdarkly/go-jsonstream/v3 for more details.

type ValueArray

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

ValueArray is an immutable array of [Value]s.

This is used internally to hold the contents of a JSON array in a Value. You can also use it separately in any context where you know that the data must be array-like, rather than any of the other types that a Value can be.

The wrapped slice is not directly accessible, so it cannot be modified. You can obtain a copy of it with ValueArray.AsSlice if necessary.

Like a Go slice, there is a distinction between an array in a nil state-- which is the zero value of ValueArray{}-- and a non-nil aray that is empty. The former is represented in JSON as a null; the latter is an empty JSON array [].

func CopyArbitraryValueArray

func CopyArbitraryValueArray(data []any) ValueArray

CopyArbitraryValueArray copies an existing ordinary slice of values of any type to a ValueArray. The behavior for each value is the same as CopyArbitraryValue.

If the parameter is nil, an uninitialized ValueArray{} is returned instead of a zero-length map.

func CopyValueArray

func CopyValueArray(data []Value) ValueArray

CopyValueArray copies an existing ordinary map to a ValueArray.

If the parameter is nil, an uninitialized ValueArray{} is returned instead of a zero-length array.

func ValueArrayOf

func ValueArrayOf(items ...Value) ValueArray

ValueArrayOf creates a ValueArray from a list of [Value]s.

This requires a slice copy to ensure immutability; otherwise, an existing slice could be passed using the spread operator, and then modified. However, since Value is itself immutable, it does not need to deep-copy each item.

func (ValueArray) AsArbitraryValueSlice

func (a ValueArray) AsArbitraryValueSlice() []any

AsArbitraryValueSlice returns a copy of the wrapped data as a simple Go slice whose values are of any type. The behavior for each value is the same as Value.AsArbitraryValue.

For an uninitialized ValueArray{}, this returns nil.

func (ValueArray) AsSlice

func (a ValueArray) AsSlice() []Value

AsSlice returns a copy of the wrapped data as a simple Go slice whose values are of type Value.

For an uninitialized ValueArray{}, this returns nil.

func (ValueArray) AsValue

func (a ValueArray) AsValue() Value

AsValue converts the ValueArray to a Value which is either Null() or an array. This does not cause any new allocations.

func (ValueArray) Count

func (a ValueArray) Count() int

Count returns the number of elements in the array. For an uninitialized ValueArray{}, this is zero.

func (ValueArray) Equal

func (a ValueArray) Equal(other ValueArray) bool

Equal returns true if the two arrays are deeply equal. Nil and zero-length arrays are not considered equal to each other.

func (ValueArray) Get

func (a ValueArray) Get(index int) Value

Get gets a value from the array by index.

If the index is out of range, it returns Null().

func (ValueArray) IsDefined

func (a ValueArray) IsDefined() bool

IsDefined returns true if the array is non-nil.

func (ValueArray) JSONString

func (a ValueArray) JSONString() string

JSONString returns the JSON representation of the array.

func (ValueArray) MarshalJSON

func (a ValueArray) MarshalJSON() ([]byte, error)

MarshalJSON converts the ValueArray to its JSON representation.

Like a Go slice, a ValueArray in an uninitialized/nil state produces a JSON null rather than an empty [].

func (ValueArray) MarshalText

func (a ValueArray) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

This may be useful with packages that support describing arbitrary types via that interface.

The behavior for ValueArray is the same as ValueArray.MarshalJSON.

func (*ValueArray) ReadFromJSONReader

func (a *ValueArray) ReadFromJSONReader(r *jreader.Reader)

ReadFromJSONReader provides JSON deserialization for use with the jsonstream API.

This implementation is used by the SDK in cases where it is more efficient than json.Unmarshal. See github.com/launchdarkly/go-jsonstream/v3 for more details.

func (ValueArray) String

func (a ValueArray) String() string

String converts the value to a string representation, equivalent to ValueArray.JSONString.

This method is provided because it is common to use the Stringer interface as a quick way to summarize the contents of a value. The simplest way to do so in this case is to use the JSON representation.

func (ValueArray) Transform

func (a ValueArray) Transform(fn func(index int, value Value) (Value, bool)) ValueArray

Transform applies a transformation function to a ValueArray, returning a new ValueArray.

The behavior is as follows:

If the input value is nil or zero-length, the result is identical and the function is not called.

Otherwise, fn is called for each value. It should return a transformed value and true, or else return false for the second return value if the property should be dropped.

func (ValueArray) TryGet

func (a ValueArray) TryGet(index int) (Value, bool)

TryGet gets a value from the map by index, with a second return value of true if successful.

If the index is out of range, it returns (Null(), false).

func (*ValueArray) UnmarshalJSON

func (a *ValueArray) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a ValueArray from JSON.

func (*ValueArray) UnmarshalText

func (a *ValueArray) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

This may be useful with packages that support parsing arbitrary types via that interface, such as gcfg.

The behavior for ValueArray is the same as ValueArray.UnmarshalJSON.

func (ValueArray) WriteToJSONWriter

func (a ValueArray) WriteToJSONWriter(w *jwriter.Writer)

WriteToJSONWriter provides JSON serialization for use with the jsonstream API.

This implementation is used by the SDK in cases where it is more efficient than json.Marshal. See github.com/launchdarkly/go-jsonstream/v3 for more details.

Like a Go slice, a ValueArray in an uninitialized/nil state produces a JSON null rather than an empty [].

type ValueArrayBuilder

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

ValueArrayBuilder is a builder created by ValueArrayBuild, for creating immutable JSON arrays.

A ValueArrayBuilder should not be accessed by multiple goroutines at once.

func ValueArrayBuild

func ValueArrayBuild() *ValueArrayBuilder

ValueArrayBuild creates a builder for constructing an immutable ValueArray.

ValueArray := ldvalue.ValueArrayBuild().Add(ldvalue.Int(100)).Add(ldvalue.Int(200)).Build()

func ValueArrayBuildFromArray

func ValueArrayBuildFromArray(a ValueArray) *ValueArrayBuilder

ValueArrayBuildFromArray creates a builder for constructing an immutable ValueArray, initializing it from an existing ValueArray.

The builder has copy-on-write behavior, so if you make no changes before calling Build(), the original array is used as-is.

func ValueArrayBuildWithCapacity

func ValueArrayBuildWithCapacity(capacity int) *ValueArrayBuilder

ValueArrayBuildWithCapacity creates a builder for constructing an immutable ValueArray.

The capacity parameter is the same as the capacity of a slice, allowing you to preallocate space if you know the number of elements; otherwise you can pass zero.

arrayValue := ldvalue.ValueArrayBuildWithCapacity(2).Add(ldvalue.Int(100)).Add(ldvalue.Int(200)).Build()

func (*ValueArrayBuilder) Add

func (b *ValueArrayBuilder) Add(value Value) *ValueArrayBuilder

Add appends an element to the array builder.

func (*ValueArrayBuilder) AddAllFromValueArray

func (b *ValueArrayBuilder) AddAllFromValueArray(a ValueArray) *ValueArrayBuilder

AddAllFromValueArray appends all elements from an existing ValueArray.

func (*ValueArrayBuilder) Build

func (b *ValueArrayBuilder) Build() ValueArray

Build creates a ValueArray containing the previously added array elements. Continuing to modify the same builder by calling Add after that point does not affect the returned array.

type ValueMap

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

ValueMap is an immutable map of string keys to Value values.

This is used internally to hold the properties of a JSON object in a Value. You can also use it separately in any context where you know that the data must be map-like, rather than any of the other types that a Value can be.

The wrapped map is not directly accessible, so it cannot be modified. You can obtain a copy of it with AsMap() if necessary.

Like a Go map, there is a distinction between a map in a nil state-- which is the zero value of ValueMap{}-- and a non-nil map that is empty. The former is represented in JSON as a null; the latter is an empty JSON object {}.

func CopyArbitraryValueMap

func CopyArbitraryValueMap(data map[string]any) ValueMap

CopyArbitraryValueMap copies an existing ordinary map of values of any type to a ValueMap. The behavior for each value is the same as CopyArbitraryValue.

If the parameter is nil, an uninitialized ValueMap{} is returned instead of a zero-length map.

func CopyValueMap

func CopyValueMap(data map[string]Value) ValueMap

CopyValueMap copies an existing ordinary map to a ValueMap.

If the parameter is nil, an uninitialized ValueMap{} is returned instead of a zero-length map.

func (ValueMap) AsArbitraryValueMap

func (m ValueMap) AsArbitraryValueMap() map[string]any

AsArbitraryValueMap returns a copy of the wrapped data as a simple Go map whose values are of any type. The behavior for each value is the same as Value.AsArbitraryValue().

For an uninitialized ValueMap{}, this returns nil.

func (ValueMap) AsMap

func (m ValueMap) AsMap() map[string]Value

AsMap returns a copy of the wrapped data as a simple Go map whose values are of type Value.

For an uninitialized ValueMap{}, this returns nil.

func (ValueMap) AsValue

func (m ValueMap) AsValue() Value

AsValue converts the ValueMap to a Value which is either Null() or an object. This does not cause any new allocations.

func (ValueMap) Count

func (m ValueMap) Count() int

Count returns the number of keys in the map. For an uninitialized ValueMap{}, this is zero.

func (ValueMap) Equal

func (m ValueMap) Equal(other ValueMap) bool

Equal returns true if the two maps are deeply equal. Nil and zero-length maps are not considered equal to each other.

func (ValueMap) Get

func (m ValueMap) Get(key string) Value

Get gets a value from the map by key.

If the key is not found, it returns Null().

func (ValueMap) IsDefined

func (m ValueMap) IsDefined() bool

IsDefined returns true if the map is non-nil.

func (ValueMap) JSONString

func (m ValueMap) JSONString() string

JSONString returns the JSON representation of the map.

func (ValueMap) Keys

func (m ValueMap) Keys(sliceIn []string) []string

Keys returns the keys of a the map as a slice.

If a non-nil slice is passed in, it will be reused to hold the return values if it has enough capacity. Otherwise, a new slice is allocated if there are any keys.

The ordering of the keys is undefined.

func (ValueMap) MarshalJSON

func (m ValueMap) MarshalJSON() ([]byte, error)

MarshalJSON converts the ValueMap to its JSON representation.

Like a Go map, a ValueMap in an uninitialized/nil state produces a JSON null rather than an empty {}.

func (ValueMap) MarshalText

func (m ValueMap) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

This may be useful with packages that support describing arbitrary types via that interface.

The behavior for ValueMap is the same as ValueMap.MarshalJSON.

func (*ValueMap) ReadFromJSONReader

func (m *ValueMap) ReadFromJSONReader(r *jreader.Reader)

ReadFromJSONReader provides JSON deserialization for use with the jsonstream API.

This implementation is used by the SDK in cases where it is more efficient than json.Unmarshal. See github.com/launchdarkly/go-jsonstream/v3 for more details.

func (ValueMap) String

func (m ValueMap) String() string

String converts the value to a map representation, equivalent to JSONString().

This method is provided because it is common to use the Stringer interface as a quick way to summarize the contents of a value. The simplest way to do so in this case is to use the JSON representation.

func (ValueMap) Transform

func (m ValueMap) Transform(fn func(key string, value Value) (string, Value, bool)) ValueMap

Transform applies a transformation function to a ValueMap, returning a new ValueMap.

The behavior is as follows:

If the input value is nil or zero-length, the result is identical and the function is not called.

Otherwise, fn is called for each key-value pair. It should return a transformed key-value pair and true, or else return false for the third return value if the property should be dropped.

func (ValueMap) TryGet

func (m ValueMap) TryGet(key string) (Value, bool)

TryGet gets a value from the map by key, with a second return value of true if successful.

If the key is not found, it returns (Null(), false).

func (*ValueMap) UnmarshalJSON

func (m *ValueMap) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a ValueMap from JSON.

func (*ValueMap) UnmarshalText

func (m *ValueMap) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

This may be useful with packages that support parsing arbitrary types via that interface, such as gcfg.

The behavior for ValueMap is the same as ValueMap.UnmarshalJSON.

func (ValueMap) WriteToJSONWriter

func (m ValueMap) WriteToJSONWriter(w *jwriter.Writer)

WriteToJSONWriter provides JSON serialization for use with the jsonstream API.

This implementation is used by the SDK in cases where it is more efficient than json.Marshal. See github.com/launchdarkly/go-jsonstream/v3 for more details.

Like a Go map, a ValueMap in an uninitialized/nil state produces a JSON null rather than an empty {}.

type ValueMapBuilder

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

ValueMapBuilder is a builder created by ValueMapBuild(), for creating immutable JSON objects.

A ValueMapBuilder should not be accessed by multiple goroutines at once.

func ValueMapBuild

func ValueMapBuild() *ValueMapBuilder

ValueMapBuild creates a builder for constructing an immutable ValueMap.

valueMap := ldvalue.ValueMapBuild().Set("a", ldvalue.Int(100)).Set("b", ldvalue.Int(200)).Build()

func ValueMapBuildFromMap

func ValueMapBuildFromMap(m ValueMap) *ValueMapBuilder

ValueMapBuildFromMap creates a builder for constructing an immutable ValueMap, initializing it from an existing ValueMap.

The builder has copy-on-write behavior, so if you make no changes before calling Build(), the original map is used as-is.

func ValueMapBuildWithCapacity

func ValueMapBuildWithCapacity(capacity int) *ValueMapBuilder

ValueMapBuildWithCapacity creates a builder for constructing an immutable ValueMap.

The capacity parameter is the same as the capacity of a map, allowing you to preallocate space if you know the number of elements; otherwise you can pass zero.

objValue := ldvalue.ObjectBuildWithCapacity(2).Set("a", ldvalue.Int(100)).Set("b", ldvalue.Int(200)).Build()

func (*ValueMapBuilder) Build

func (b *ValueMapBuilder) Build() ValueMap

Build creates a ValueMap containing the previously specified key-value pairs. Continuing to modify the same builder by calling Set after that point does not affect the returned ValueMap.

func (*ValueMapBuilder) HasKey

func (b *ValueMapBuilder) HasKey(key string) bool

HasKey returns true if the specified key has been set in the builder.

func (*ValueMapBuilder) Remove

func (b *ValueMapBuilder) Remove(key string) *ValueMapBuilder

Remove unsets a key if it was set.

func (*ValueMapBuilder) Set

func (b *ValueMapBuilder) Set(key string, value Value) *ValueMapBuilder

Set sets a key-value pair in the map builder.

func (*ValueMapBuilder) SetAllFromValueMap

func (b *ValueMapBuilder) SetAllFromValueMap(m ValueMap) *ValueMapBuilder

SetAllFromValueMap copies all key-value pairs from an existing ValueMap.

type ValueType

type ValueType int

ValueType indicates which JSON type is contained in a Value.

const (
	// NullType describes a null value. Note that the zero value of ValueType is NullType, so the
	// zero of Value is a null value. See [Null].
	NullType ValueType = iota
	// BoolType describes a boolean value. See [Bool].
	BoolType ValueType = iota
	// NumberType describes a numeric value. JSON does not have separate types for int and float, but
	// you can convert to either. See [Int] and [Float64].
	NumberType ValueType = iota
	// StringType describes a string value. See [String].
	StringType ValueType = iota
	// ArrayType describes an array value. See [ArrayOf] and [ArrayBuild].
	ArrayType ValueType = iota
	// ObjectType describes an object (a.k.a. map). See [ObjectBuild].
	ObjectType ValueType = iota
	// RawType describes a json.RawMessage value. See [Raw].
	RawType ValueType = iota
)

func (ValueType) String

func (t ValueType) String() string

String returns the name of the value type.

Jump to

Keyboard shortcuts

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