Unmarshal map[string]types.AttributeValue to specific business model / struct
Asked Answered
E

3

6

I am trying to use AWS SDK GO v2: https://github.com/aws/aws-sdk-go-v2 And seem to have a hard time unmarshalling the dynamodb.GetItemOutput's Item attribute which is of type map[string]types.AttributeValue.

in AWS SDK GO v1, it's easy to call dynamodbattribute.UnmarshalMap(result.Item, &data) to unmarshal the result. But on v2, I can't find any way to do this.

does anyone have an idea how to do it ?

Exuberate answered 6/1, 2021 at 5:28 Comment(0)
E
5

I was able to find an answer, thanks to Sean McGrail, one of the contributors of the aws-sdk-go-v2 project. The attributevalue library has methods to unmarshal and marshal the query results to your specific business model/struct:

https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue

I just needed to manually import this library since this wasn't pre-included during download of aws-sdk-go-v2:

go get github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue
Exuberate answered 6/1, 2021 at 20:16 Comment(0)
M
5

Using github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue You can unmarshal each result item returned by the "Scan" API into a go struct.

var object struct {
    PropertyA string `json:"property_a"`
    PropertyB  string `json:"property_b"`
}

_ = attributevalue.UnmarshalMap(<item>, &object)
Margiemargin answered 6/11, 2021 at 13:27 Comment(0)
O
-2

Whenever I have to unmarshall JSON data, which is the default output of most AWS SDK responses, I:

  1. Barf out the entire JSON blob (fmt.Println(result))
  2. Copy and paste that into https://mholt.github.io/json-to-go
  3. Snarf the resulting struct into my code, say as MyStruct
  4. Call json.Unmarshal([]byte(result), &MyStruct)
Oira answered 6/1, 2021 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.