Documentation ¶
Overview ¶
Package dynamodbattribute provides marshaling utilities for marshaling to dynamodb.AttributeValue types and unmarshaling to Go value types. These utilities allow you to marshal slices, maps, structs, and scalar values to and from dynamodb.AttributeValue. These are useful when marshaling Go value tyes to dynamodb.AttributeValue for DynamoDB requests, or unmarshaling the dynamodb.AttributeValue back into a Go value type.
Marshal Go value types to dynamodb.AttributeValue: See (ExampleMarshal)
type Record struct { MyField string Letters []string A2Num map[string]int } ... r := Record{ MyField: "dynamodbattribute.Marshal example", Letters: []string{"a", "b", "c", "d"}, A2Num: map[string]int{"a": 1, "b": 2, "c": 3}, } av, err := dynamodbattribute.Marshal(r) fmt.Println(av, err)
Unmarshal dynamodb.AttributeValue to Go value type: See (ExampleUnmarshal)
r2 := Record{} err = dynamodbattribute.Unmarshal(av, &r2) fmt.Println(err, reflect.DeepEqual(r, r2))
Marshal Go value type for DynamoDB.PutItem:
sess := session.Must(session.NewSession()) svc := dynamodb.New(sess) item, err := dynamodbattribute.MarshalMap(r) if err != nil { fmt.Println("Failed to convert", err) return } result, err := svc.PutItem(&dynamodb.PutItemInput{ Item: item, TableName: aws.String("exampleTable"), })
The ConvertTo, ConvertToList, ConvertToMap, ConvertFrom, ConvertFromMap and ConvertFromList methods have been deprecated. The Marshal and Unmarshal functions should be used instead. The ConvertTo|From marshallers do not support BinarySet, NumberSet, nor StringSets, and will incorrect marshal binary data fields in structs as base64 strings.
The Marshal and Unmarshal functions correct this behavior, and removes the reliance on encoding.json. `json` struct tags are still supported. In addition support for a new struct tag `dynamodbav` was added. Support for the json.Marshaler and json.Unmarshaler interfaces have been removed and replaced with have been replaced with dynamodbattribute.Marshaler and dynamodbattribute.Unmarshaler interfaces.
`time.Time` is marshaled as RFC3339 format.
Index ¶
- func ConvertFrom(item *dynamodb.AttributeValue, v interface{}) (err error)deprecated
- func ConvertFromList(item []*dynamodb.AttributeValue, v interface{}) (err error)deprecated
- func ConvertFromMap(item map[string]*dynamodb.AttributeValue, v interface{}) (err error)deprecated
- func ConvertTo(in interface{}) (item *dynamodb.AttributeValue, err error)deprecated
- func ConvertToList(in interface{}) (item []*dynamodb.AttributeValue, err error)deprecated
- func ConvertToMap(in interface{}) (item map[string]*dynamodb.AttributeValue, err error)deprecated
- func Marshal(in interface{}) (*dynamodb.AttributeValue, error)
- func MarshalList(in interface{}) ([]*dynamodb.AttributeValue, error)
- func MarshalMap(in interface{}) (map[string]*dynamodb.AttributeValue, error)
- func Unmarshal(av *dynamodb.AttributeValue, out interface{}) error
- func UnmarshalList(l []*dynamodb.AttributeValue, out interface{}) error
- func UnmarshalListOfMaps(l []map[string]*dynamodb.AttributeValue, out interface{}) error
- func UnmarshalMap(m map[string]*dynamodb.AttributeValue, out interface{}) error
- type Decoder
- type Encoder
- type InvalidMarshalError
- type InvalidUnmarshalError
- type MarshalOptions
- type Marshaler
- type Number
- type UnixTime
- type UnmarshalError
- type UnmarshalTypeError
- type Unmarshaler
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ConvertFrom
deprecated
func ConvertFrom(item *dynamodb.AttributeValue, v interface{}) (err error)
ConvertFrom accepts a *dynamodb.AttributeValue and converts it to any interface{}.
If v contains any structs, the result is first converted it to a interface{}, then JSON encoded/decoded it to convert to a struct, so `json` struct tags are respected.
Deprecated: Use Unmarshal instead
Example ¶
package main import ( "fmt" "reflect" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" ) func main() { type Record struct { MyField string Letters []string A2Num map[string]int } r := Record{ MyField: "MyFieldValue", Letters: []string{"a", "b", "c", "d"}, A2Num: map[string]int{"a": 1, "b": 2, "c": 3}, } av, err := dynamodbattribute.ConvertTo(r) r2 := Record{} err = dynamodbattribute.ConvertFrom(av, &r2) fmt.Println(err, reflect.DeepEqual(r, r2)) }
Output: <nil> true
func ConvertFromList
deprecated
func ConvertFromList(item []*dynamodb.AttributeValue, v interface{}) (err error)
ConvertFromList accepts a []*dynamodb.AttributeValue and converts it to an array or slice.
If v contains any structs, the result is first converted it to a []interface{}, then JSON encoded/decoded it to convert to a typed array or slice, so `json` struct tags are respected.
Deprecated: Use UnmarshalList instead
func ConvertFromMap
deprecated
func ConvertFromMap(item map[string]*dynamodb.AttributeValue, v interface{}) (err error)
ConvertFromMap accepts a map[string]*dynamodb.AttributeValue and converts it to a map[string]interface{} or struct.
If v points to a struct, the result is first converted it to a map[string]interface{}, then JSON encoded/decoded it to convert to a struct, so `json` struct tags are respected.
Deprecated: Use UnmarshalMap instead
func ConvertTo
deprecated
func ConvertTo(in interface{}) (item *dynamodb.AttributeValue, err error)
ConvertTo accepts any interface{} and converts it to a *dynamodb.AttributeValue.
If in contains any structs, it is first JSON encoded/decoded it to convert it to a interface{}, so `json` struct tags are respected.
Deprecated: Use Marshal instead
Example ¶
package main import ( "fmt" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" ) func main() { type Record struct { MyField string Letters []string Numbers []int } r := Record{ MyField: "MyFieldValue", Letters: []string{"a", "b", "c", "d"}, Numbers: []int{1, 2, 3}, } av, err := dynamodbattribute.ConvertTo(r) fmt.Println("err", err) fmt.Println("MyField", av.M["MyField"]) fmt.Println("Letters", av.M["Letters"]) fmt.Println("Numbers", av.M["Numbers"]) }
Output: err <nil> MyField { S: "MyFieldValue" } Letters { L: [ { S: "a" }, { S: "b" }, { S: "c" }, { S: "d" } ] } Numbers { L: [{ N: "1" },{ N: "2" },{ N: "3" }] }
func ConvertToList
deprecated
func ConvertToList(in interface{}) (item []*dynamodb.AttributeValue, err error)
ConvertToList accepts an array or slice and converts it to a []*dynamodb.AttributeValue.
Converting []byte fields to dynamodb.AttributeValue are only currently supported if the input is a map[string]interface{} type. []byte within typed structs are not converted correctly and are converted into base64 strings. This is a known bug, and will be fixed in a later release.
If in contains any structs, it is first JSON encoded/decoded it to convert it to a []interface{}, so `json` struct tags are respected.
Deprecated: Use MarshalList instead
func ConvertToMap
deprecated
func ConvertToMap(in interface{}) (item map[string]*dynamodb.AttributeValue, err error)
ConvertToMap accepts a map[string]interface{} or struct and converts it to a map[string]*dynamodb.AttributeValue.
If in contains any structs, it is first JSON encoded/decoded it to convert it to a map[string]interface{}, so `json` struct tags are respected.
Deprecated: Use MarshalMap instead
func Marshal ¶ added in v1.1.16
func Marshal(in interface{}) (*dynamodb.AttributeValue, error)
Marshal will serialize the passed in Go value type into a DynamoDB AttributeValue type. This value can be used in DynamoDB API operations to simplify marshaling your Go value types into AttributeValues.
Marshal will recursively transverse the passed in value marshaling its contents into a AttributeValue. Marshal supports basic scalars (int,uint,float,bool,string), maps, slices, and structs. Anonymous nested types are flattened based on Go anonymous type visibility.
Marshaling slices to AttributeValue will default to a List for all types except for []byte and [][]byte. []byte will be marshaled as Binary data (B), and [][]byte will be marshaled as binary data set (BS).
`dynamodbav` struct tag can be used to control how the value will be marshaled into a AttributeValue.
// Field is ignored Field int `dynamodbav:"-"` // Field AttributeValue map key "myName" Field int `dynamodbav:"myName"` // Field AttributeValue map key "myName", and // Field is omitted if it is empty Field int `dynamodbav:"myName,omitempty"` // Field AttributeValue map key "Field", and // Field is omitted if it is empty Field int `dynamodbav:",omitempty"` // Field's elems will be omitted if empty // only valid for slices, and maps. Field []string `dynamodbav:",omitemptyelem"` // Field will be marshaled as a AttributeValue string // only value for number types, (int,uint,float) Field int `dynamodbav:",string"` // Field will be marshaled as a binary set Field [][]byte `dynamodbav:",binaryset"` // Field will be marshaled as a number set Field []int `dynamodbav:",numberset"` // Field will be marshaled as a string set Field []string `dynamodbav:",stringset"` // Field will be marshaled as Unix time number in seconds. // This tag is only valid with time.Time typed struct fields. // Important to note that zero value time as unixtime is not 0 seconds // from January 1, 1970 UTC, but -62135596800. Which is seconds between // January 1, 0001 UTC, and January 1, 0001 UTC. Field time.Time `dynamodbav:",unixtime"`
The omitempty tag is only used during Marshaling and is ignored for Unmarshal. Any zero value or a value when marshaled results in a AttributeValue NULL will be added to AttributeValue Maps during struct marshal. The omitemptyelem tag works the same as omitempty except it applies to maps and slices instead of struct fields, and will not be included in the marshaled AttributeValue Map, List, or Set.
For convenience and backwards compatibility with ConvertTo functions json struct tags are supported by the Marshal and Unmarshal. If both json and dynamodbav struct tags are provided the json tag will be ignored in favor of dynamodbav.
All struct fields and with anonymous fields, are marshaled unless the any of the following conditions are meet.
- the field is not exported
- json or dynamodbav field tag is "-"
- json or dynamodbav field tag specifies "omitempty", and is empty.
Pointer and interfaces values encode as the value pointed to or contained in the interface. A nil value encodes as the AttributeValue NULL value.
Channel, complex, and function values are not encoded and will be skipped when walking the value to be marshaled.
When marshaling any error that occurs will halt the marshal and return the error.
Marshal cannot represent cyclic data structures and will not handle them. Passing cyclic structures to Marshal will result in an infinite recursion.
Example ¶
package main import ( "fmt" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" ) func main() { type Record struct { Bytes []byte MyField string Letters []string Numbers []int } r := Record{ Bytes: []byte{48, 49}, MyField: "MyFieldValue", Letters: []string{"a", "b", "c", "d"}, Numbers: []int{1, 2, 3}, } av, err := dynamodbattribute.Marshal(r) fmt.Println("err", err) fmt.Println("Bytes", av.M["Bytes"]) fmt.Println("MyField", av.M["MyField"]) fmt.Println("Letters", av.M["Letters"]) fmt.Println("Numbers", av.M["Numbers"]) }
Output: err <nil> Bytes { B: <binary> len 2 } MyField { S: "MyFieldValue" } Letters { L: [ { S: "a" }, { S: "b" }, { S: "c" }, { S: "d" } ] } Numbers { L: [{ N: "1" },{ N: "2" },{ N: "3" }] }
func MarshalList ¶ added in v1.1.16
func MarshalList(in interface{}) ([]*dynamodb.AttributeValue, error)
MarshalList is an alias for Marshal func which marshals Go value type to a slice of AttributeValues.
func MarshalMap ¶ added in v1.1.16
func MarshalMap(in interface{}) (map[string]*dynamodb.AttributeValue, error)
MarshalMap is an alias for Marshal func which marshals Go value type to a map of AttributeValues.
func Unmarshal ¶ added in v1.1.16
func Unmarshal(av *dynamodb.AttributeValue, out interface{}) error
Unmarshal will unmarshal DynamoDB AttributeValues to Go value types. Both generic interface{} and concrete types are valid unmarshal destination types.
Unmarshal will allocate maps, slices, and pointers as needed to unmarshal the AttributeValue into the provided type value.
When unmarshaling AttributeValues into structs Unmarshal matches the field names of the struct to the AttributeValue Map keys. Initially it will look for exact field name matching, but will fall back to case insensitive if not exact match is found.
With the exception of omitempty, omitemptyelem, binaryset, numberset and stringset all struct tags used by Marshal are also used by Unmarshal.
When decoding AttributeValues to interfaces Unmarshal will use the following types.
[]byte, AV Binary (B) [][]byte, AV Binary Set (BS) bool, AV Boolean (BOOL) []interface{}, AV List (L) map[string]interface{}, AV Map (M) float64, AV Number (N) Number, AV Number (N) with UseNumber set []float64, AV Number Set (NS) []Number, AV Number Set (NS) with UseNumber set string, AV String (S) []string, AV String Set (SS)
If the Decoder option, UseNumber is set numbers will be unmarshaled as Number values instead of float64. Use this to maintain the original string formating of the number as it was represented in the AttributeValue. In addition provides additional opportunities to parse the number string based on individual use cases.
When unmarshaling any error that occurs will halt the unmarshal and return the error.
The output value provided must be a non-nil pointer
Example ¶
package main import ( "fmt" "reflect" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" ) func main() { type Record struct { Bytes []byte MyField string Letters []string A2Num map[string]int } expect := Record{ Bytes: []byte{48, 49}, MyField: "MyFieldValue", Letters: []string{"a", "b", "c", "d"}, A2Num: map[string]int{"a": 1, "b": 2, "c": 3}, } av := &dynamodb.AttributeValue{ M: map[string]*dynamodb.AttributeValue{ "Bytes": {B: []byte{48, 49}}, "MyField": {S: aws.String("MyFieldValue")}, "Letters": {L: []*dynamodb.AttributeValue{ {S: aws.String("a")}, {S: aws.String("b")}, {S: aws.String("c")}, {S: aws.String("d")}, }}, "A2Num": {M: map[string]*dynamodb.AttributeValue{ "a": {N: aws.String("1")}, "b": {N: aws.String("2")}, "c": {N: aws.String("3")}, }}, }, } actual := Record{} err := dynamodbattribute.Unmarshal(av, &actual) fmt.Println(err, reflect.DeepEqual(expect, actual)) }
Output: <nil> true
func UnmarshalList ¶ added in v1.1.16
func UnmarshalList(l []*dynamodb.AttributeValue, out interface{}) error
UnmarshalList is an alias for Unmarshal func which unmarshals a slice of AttributeValues.
The output value provided must be a non-nil pointer
func UnmarshalListOfMaps ¶ added in v1.4.20
func UnmarshalListOfMaps(l []map[string]*dynamodb.AttributeValue, out interface{}) error
UnmarshalListOfMaps is an alias for Unmarshal func which unmarshals a slice of maps of attribute values.
This is useful for when you need to unmarshal the Items from a DynamoDB Query API call.
The output value provided must be a non-nil pointer
func UnmarshalMap ¶ added in v1.1.16
func UnmarshalMap(m map[string]*dynamodb.AttributeValue, out interface{}) error
UnmarshalMap is an alias for Unmarshal which unmarshals from a map of AttributeValues.
The output value provided must be a non-nil pointer
Types ¶
type Decoder ¶ added in v1.1.16
type Decoder struct { MarshalOptions // Instructs the decoder to decode AttributeValue Numbers as // Number type instead of float64 when the destination type // is interface{}. Similar to encoding/json.Number UseNumber bool }
A Decoder provides unmarshaling AttributeValues to Go value types.
func NewDecoder ¶ added in v1.1.16
NewDecoder creates a new Decoder with default configuration. Use the `opts` functional options to override the default configuration.
func (*Decoder) Decode ¶ added in v1.1.16
func (d *Decoder) Decode(av *dynamodb.AttributeValue, out interface{}, opts ...func(*Decoder)) error
Decode will unmarshal an AttributeValue into a Go value type. An error will be return if the decoder is unable to unmarshal the AttributeValue to the provide Go value type.
The output value provided must be a non-nil pointer
type Encoder ¶ added in v1.1.16
type Encoder struct { MarshalOptions // Empty strings, "", will be marked as NULL AttributeValue types. // Empty strings are not valid values for DynamoDB. Will not apply // to lists, sets, or maps. Use the struct tag `omitemptyelem` // to skip empty (zero) values in lists, sets and maps. // // Enabled by default. NullEmptyString bool }
An Encoder provides marshaling Go value types to AttributeValues.
func NewEncoder ¶ added in v1.1.16
NewEncoder creates a new Encoder with default configuration. Use the `opts` functional options to override the default configuration.
type InvalidMarshalError ¶ added in v1.1.16
type InvalidMarshalError struct {
// contains filtered or unexported fields
}
An InvalidMarshalError is an error type representing an error occurring when marshaling a Go value type to an AttributeValue.
func (*InvalidMarshalError) Code ¶ added in v1.1.16
func (e *InvalidMarshalError) Code() string
Code returns the code of the error, satisfying the awserr.Error interface.
func (*InvalidMarshalError) Error ¶ added in v1.1.16
func (e *InvalidMarshalError) Error() string
Error returns the string representation of the error. satisfying the error interface
func (*InvalidMarshalError) Message ¶ added in v1.1.16
func (e *InvalidMarshalError) Message() string
Message returns the detailed message of the error, satisfying the awserr.Error interface.
type InvalidUnmarshalError ¶ added in v1.1.16
An InvalidUnmarshalError is an error type representing an invalid type encountered while unmarshaling a AttributeValue to a Go value type.
func (*InvalidUnmarshalError) Code ¶ added in v1.1.16
func (e *InvalidUnmarshalError) Code() string
Code returns the code of the error, satisfying the awserr.Error interface.
func (*InvalidUnmarshalError) Error ¶ added in v1.1.16
func (e *InvalidUnmarshalError) Error() string
Error returns the string representation of the error. satisfying the error interface
func (*InvalidUnmarshalError) Message ¶ added in v1.1.16
func (e *InvalidUnmarshalError) Message() string
Message returns the detailed message of the error, satisfying the awserr.Error interface.
type MarshalOptions ¶ added in v1.1.16
type MarshalOptions struct { // States that the encoding/json struct tags should be supported. // if a `dynamodbav` struct tag is also provided the encoding/json // tag will be ignored. // // Enabled by default. SupportJSONTags bool }
A MarshalOptions is a collection of options shared between marshaling and unmarshaling
type Marshaler ¶ added in v1.1.16
type Marshaler interface {
MarshalDynamoDBAttributeValue(*dynamodb.AttributeValue) error
}
A Marshaler is an interface to provide custom marshaling of Go value types to AttributeValues. Use this to provide custom logic determining how a Go Value type should be marshaled.
type ExampleMarshaler struct { Value int } type (m *ExampleMarshaler) MarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error { n := fmt.Sprintf("%v", m.Value) av.N = &n return nil }
type Number ¶ added in v1.1.16
type Number string
A Number represents a Attributevalue number literal.
func (Number) Float64 ¶ added in v1.1.16
Float64 attempts to cast the number ot a float64, returning the result of the case or error if the case failed.
func (Number) Int64 ¶ added in v1.1.16
Int64 attempts to cast the number ot a int64, returning the result of the case or error if the case failed.
type UnixTime ¶ added in v1.7.9
An UnixTime provides aliasing of time.Time into a type that when marshaled and unmarshaled with DynamoDB AttributeValues it will be done so as number instead of string in seconds since January 1, 1970 UTC.
This type is useful as an alterntitive to the struct tag `unixtime` when you want to have your time value marshaled as Unix time in seconds intead of the default time.RFC3339.
Important to note that zero value time as unixtime is not 0 seconds from January 1, 1970 UTC, but -62135596800. Which is seconds between January 1, 0001 UTC, and January 1, 0001 UTC.
func (UnixTime) MarshalDynamoDBAttributeValue ¶ added in v1.7.9
func (e UnixTime) MarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error
MarshalDynamoDBAttributeValue implements the Marshaler interface so that the UnixTime can be marshaled from to a DynamoDB AttributeValue number value encoded in the number of seconds since January 1, 1970 UTC.
func (*UnixTime) UnmarshalDynamoDBAttributeValue ¶ added in v1.7.9
func (e *UnixTime) UnmarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error
UnmarshalDynamoDBAttributeValue implements the Unmarshaler interface so that the UnixTime can be unmarshaled from a DynamoDB AttributeValue number representing the number of seconds since January 1, 1970 UTC.
If an error parsing the AttributeValue number occurs UnmarshalError will be returned.
type UnmarshalError ¶ added in v1.7.9
An UnmarshalError wraps an error that occured while unmarshaling a DynamoDB AttributeValue element into a Go type. This is different from UnmarshalTypeError in that it wraps the underlying error that occured.
func (*UnmarshalError) Code ¶ added in v1.7.9
func (e *UnmarshalError) Code() string
Code returns the code of the error, satisfying the awserr.Error interface.
func (*UnmarshalError) Error ¶ added in v1.7.9
func (e *UnmarshalError) Error() string
Error returns the string representation of the error. satisfying the error interface.
func (*UnmarshalError) Message ¶ added in v1.7.9
func (e *UnmarshalError) Message() string
Message returns the detailed message of the error, satisfying the awserr.Error interface.
func (UnmarshalError) OrigErr ¶ added in v1.7.9
func (e UnmarshalError) OrigErr() error
OrigErr returns the original error that caused this issue.
type UnmarshalTypeError ¶ added in v1.1.16
type UnmarshalTypeError struct { Value string Type reflect.Type // contains filtered or unexported fields }
An UnmarshalTypeError is an error type representing a error unmarshaling the AttributeValue's element to a Go value type. Includes details about the AttributeValue type and Go value type.
func (*UnmarshalTypeError) Code ¶ added in v1.1.16
func (e *UnmarshalTypeError) Code() string
Code returns the code of the error, satisfying the awserr.Error interface.
func (*UnmarshalTypeError) Error ¶ added in v1.1.16
func (e *UnmarshalTypeError) Error() string
Error returns the string representation of the error. satisfying the error interface
func (*UnmarshalTypeError) Message ¶ added in v1.1.16
func (e *UnmarshalTypeError) Message() string
Message returns the detailed message of the error, satisfying the awserr.Error interface.
type Unmarshaler ¶ added in v1.1.16
type Unmarshaler interface {
UnmarshalDynamoDBAttributeValue(*dynamodb.AttributeValue) error
}
An Unmarshaler is an interface to provide custom unmarshaling of AttributeValues. Use this to provide custom logic determining how AttributeValues should be unmarshaled.
type ExampleUnmarshaler struct { Value int } type (u *exampleUnmarshaler) UnmarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error { if av.N == nil { return nil } n, err := strconv.ParseInt(*av.N, 10, 0) if err != nil { return err } u.Value = n return nil }