Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save JSON response in dynamodb in GO

I want to save a JSON response in aws-dynamodb, I am using aws-dynamodb-sdk. What I'm currently doing is:

func (e *DB) saveToDynamodb(data map[string]interface{}){
params := &dynamodb.PutItemInput{
    Item: map[string]*dynamodb.AttributeValue{
        "Key": {
            M: data,
        },
    },
    TableName: aws.String("Asset_Data"),
}
resp, err := e.dynamodb.PutItem(params)

if err != nil {
    fmt.Println(err.Error())
    return
}
fmt.Println(resp)
}

But as you can see data is of map[string]interface{} type while the expected type is map[string]*AttributeValue that's why giving compilation error.

Is there any workaround to save a json response?

like image 898
Yash Srivastava Avatar asked Jun 29 '16 13:06

Yash Srivastava


1 Answers

The best way to put json into DynamoDB is to use the helper functions.

func ExampleMarshal() (map[string]*dynamodb.AttributeValue, error) {                                                                                                    
  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)
  return map[string]*dynamodb.AttributeValue{"object":av}, err
}
like image 91
Xibz Avatar answered Sep 29 '22 07:09

Xibz